I am trying to have a menu that takes a character input for a switch case and loops till the input is q but after the loop run once i get this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(Unknown Source) at Menu.main(Menu.java:19)
Which means its getting a null input right? So i added the .trim() but i still get the error, it doesn't even wait for an input i just get the error.
Sorry if this has been answered before but i can't find it anywhere. I've also tried adding keyboard.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); which doesn't work as well.
Input given for the program with error log:
Enter Option (a,b,c,d,e,f,q):
c
Enter 2 Numbers
First Number:
1
Second Number:
10
1, 2, 3, 4, 5,
6, 7, 8, 9, 10
Enter Option (a,b,c,d,e,f,q):
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Menu.main(Menu.java:19)
CODE:
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
char ch; int m,n; String y;
do
{
System.out.println("Enter Option (a,b,c,d,e,f,q):");
ch = keyboard.nextLine().toLowerCase().charAt(0);
switch (ch)
{
case 'c':
System.out.println("Enter 2 Numbers");
System.out.println("First Number: ");
m = keyboard.nextInt();
System.out.println("Second Number: ");
n = keyboard.nextInt();
for(int i = 1; i <= n - m + 1; i++)
{
if (i % 5 == 0)
{
System.out.print(i);
if (i != n - m + 1)
{
System.out.println(", ");
}
}else
{
System.out.print(i);
if (i != n - m + 1)
{
System.out.print(", ");
}
}
}
System.out.println("");
break;
}
}while (ch != 'q');
}
}
Try the line ch = keyboard.next().charAt(0); switch(ch)
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
char ch; int m,n; String y;
do
{
System.out.println("Enter Option (a,b,c,d,e,f,q):");
ch = keyboard.next().charAt(0);
switch (ch)
{
case 'c':
System.out.println("Enter 2 Numbers");
System.out.println("First Number: ");
m = keyboard.nextInt();
System.out.println("Second Number: ");
n = keyboard.nextInt();
for(int i = 1; i <= n - m + 1; i++)
{
if (i % 5 == 0)
{
System.out.print(i);
if (i != n - m + 1)
{
System.out.println(", ");
}
}else
{
System.out.print(i);
if (i != n - m + 1)
{
System.out.print(", ");
}
}
}
System.out.println("");
break;
}
}while (ch != 'q');
}
}
Happy coding!
Main thing here that scanner works with input right just after you hit "enter".
So if your input would be entering '\u0020'(whitespaces) even several times on line 19 you're doing trim to empty line and according to javadoc charAt.
Here's the updated code Please check:
public static void main(String[] args)
{
Scanner keyboard = new Scanner (System.in);
char ch;
do
{
System.out.println("Enter Option (a,b,c,d,e,f,q):");
ch = keyboard.nextLine().toLowerCase().charAt(0);
switch (ch)
{
//case statements for a,b,c,d,e and f
}
}while (ch != 'q');
}
Related
Hello my purpose is this:
Write a method that can accept values only between 10 and 50.Sample execution:Enter a number between 10 and 50Enter a number: 5Enter a number between 10 and 50Enter a number: 12Number Entered: 12.Enter a number: 0Good ByeSo as you can see it only finishes when user enters 0.And it says different things when number is between 10 and 50 or not.I deleted again my code and started but i got stuck on some points and i gave up.My final code was:
import java.util.Scanner;
public class A{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter case number: ");
int caseVal = scan.nextInt();
switch(caseVal){
case 1:
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number: ");
int num = scan.nextInt();
betweenMethod(num);
if(num == 0){
System.out.println("Good Bye");
break;
}
while(num != 0){
betweenMethod(num);
}
break;
case 2:
System.out.println("Enter a number to display its divisors: ");
int x = scan.nextInt();
System.out.println("The divisors of " + x + " are:");
divisorsMethod(x);
break;
}
scan.close();
}
public static void divisorsMethod(int a){
if(a <= 0)
System.out.println("The number should be greater than 0");
else{
for(int b = 1; b <= a; b++){
if(a % b == 0 && b != a)
System.out.print(b + ", ");
else if(b == a)
System.out.println(b);
}
}
}
public static void betweenMethod(int a){
Scanner inputscan = new Scanner(System.in);
if(a >= 10 && a <= 50){
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else if((a < 10 || a > 50) && a != 0){
System.out.println("Enter a number between 10 and 50");
System.out.println("Enter a number:");
a = inputscan.nextInt();
}
else{
System.out.println("Good Bye");
}
inputscan.close();
}
}
Sorry for uncut version.It is case 1.Every time i tried it didnt work fully.If anyone can help i would appreciate it.I'm sorry if i didnt write this question in rules.(Sorry for the grammar as well)THIS IS WHERE I AM STUCK= When i type 0 it doesnt say GoodBye and end the loop.Thats where i need help.TO EVERYONE THAT NEEDS ANSWER TOO:I figured out what to do.Basically we say while its not equal to zero right?I wrote a new method that (after last inputscan for variable)checks if the number is zero and prints good bye.So with this way it prints good bye and it goes to starting.But it cannot do anythink else because we said while not equal to 0.Anyway thats one solution.
Don't close() System.in
When you call inputscan.close() that closes the underlying InputStream, which is System.in.
Return the Value
Your method should be prompting for input between two values and returning a single value. Also, you could move your Scanner to a static (or class) field. Something like
private static Scanner inputscan = new Scanner(System.in);
public static int betweenMethod(final int a, final int b) {
int min = Math.min(a, b);
int max = Math.max(a, b);
while (true) {
System.out.printf("Please enter a number between %d and %d%n", min, max);
int in = inputscan.nextInt();
if ((in == 0) || (in >= min && in <= max)) {
return in;
}
}
}
Primitives1 are Passed-By Value
You need to assign the result of the call back to your value when you loop. Something like,
int num = betweenMethod(10, 50);
while (num != 0) {
System.out.printf("Number Entered: %d.%n", num);
num = betweenMethod(num);
}
System.out.println("Good Bye");
break;
1and Everything Else in Java.
Hi I am trying to take in an integer between 1 and 10.
If the user does not do so would like the program to run again.
I believe that I need to use an else if statement that calls on my function but I do not know how to call functions in java.
Here is my code so far:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
if (num1 >= 1 && num1 <= 10); {
System.out.println("Input = " + num1);
}
else if {
???
}
}
}
if-else always work.
You made a mistake in the if statement.
there is no ; for an if
if (num1 >= 1 && num1 <= 10) {//no semicolon
System.out.println("Input = " + num1);
}
else if(num < 0) {//should have a condition
...
}
else
{
...
}
What happens if I put a semicolon at the end of an if statement?.
How do I ask the user again if the input is not in between 1 and 10?
Loop until you get what you want :)
Scanner sc = new Scanner(System.in);
int num = 0;
while(true)
{
num = sc.nextInt();
if(num > 0 && num < 11)
break;
System.out.println("Enter a number between 1 and 10");
}
System.out.println(num);
Since you are expecting a number between 1 to 10, but you don't know how many numbers you will get until you get a valid number, I'd suggest to use a while loop, like so:
import java.util.Scanner;
public class NumChecker {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a number between 1 and 10: ");
int num1 = in.nextInt();
while (num1 < 1 || num1 > 10) {
System.out.print("Invalid number, enter another one: ");
num1 = in.nextInt();
}
System.out.println("Input = " + num1);
}
}
Yes, this is a homework problem. I am a beginner in programming. I am good at using if/else with for loops, since my professor asked us to while loop. I am confused.This is the question...
Q1) Suppose you are writing a game-playing program that involves 2-digit numbers, each number being composed of 2 different digits. Test if whether numbers entered in a sequence are accepted to be used in this game. Test for errors in input (including type).
My while loop to check the data type works fine at first, but after an int has been entered and I can't check the data type. Can anyone explain the problem to me please? Thank you...
public static void main(String[] args){
int num = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
while(!input.hasNextInt()){
System.out.println("Not an integer,try again " + num);
input.next();
}
num = input.nextInt();
while(num != 0){
while(num < 10 || num >= 99){
System.out.println("NOT good for your game! " + num );
System.out.println("Enter a 2-digit number. The digits should be different. Zero to stop");
num = input.nextInt();
}
System.out.println("Good for your game! Play! " + num);
num = input.nextInt();
}
}
}
The while loop in the first checked the System.in is entering a digit (int) or not: while(!input.hasNextInt()), but when you first input a digit, the loop exit and it enter into the next 2 loops:
while(num != 0){
while(num < 10 || num >= 99){
and then in the end of the inner loop you have:
num = input.nextInt();
This means you already assume the next input would be an int. So if you enter a non-digit input, program will throw an exception.
I would suggest you to change the whole loop into:
public static void main(String[] args) {
int num = 1;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
if (!input.hasNextInt()) {
System.out.println("Not an integer,try again " + num);
} else {
num = input.nextInt();
if (num < 10 || num >= 99) {
System.out.println("NOT good for your game! " + num);
} else {
System.out.println("Good for your game! Play! " + num);
}
}
} while(num != 0);
input.close();
System.out.println("game stop");
}
import java.util.Scanner;
public class Number1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String prompt = "Enter a 2-digit number. The digits should be different. Zero to stop:";
getInt(sc,prompt);
}
public static void getInt(Scanner sc,String prompt) {
System.out.println(prompt);
int num;
while (!sc.hasNextInt())
{
System.out.println("Not an integer, Try again");
sc.next();
}
num = sc.nextInt();
while(num != 0) {
if (num < 10 || num >= 99 || num == 0)
{
System.out.println("Not good for your game!");
}
else
{
System.out.println("Good for your game! Play!");
}
System.out.println(prompt);
num = sc.nextInt();
}
}
}
Examples of my output:
123
output: 5
111
output: 2
Lots work but ones like the above don't add correctly... Can anyone point me in the right direction? Here is my code:
import java.util.Scanner;
public class DigitAdder {
public static void main(String [] args) {
int input;
int output = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
input = scan.nextInt();
if(input < 0) {
System.out.println("Enter a positive integer: ");
return;
}
while(input > 1) {
output = output + (input % 10);
input /= 10;
}
System.out.println(output);
}
}
Looks like you're not counting the first digit when your input starts with 1.
Try :
while(input >= 1) {
output = output + (input % 10);
input /= 10;
}
In my code below I am not sure what order to put it in to work properly.
I first want it to print out for the user to select an option which it does, then if they select 1 it asks them their name and verifies it with the loop etc.
When I enter a name it starts to just loop the question enter your name and I don't know how to fix it.
Do I need to add more statements to my program, if I do then can I still use if statements for the user to select an option?
import java.util.Scanner;
public class username {
public static void main(String[] args) {
{
int UseLift;
int AuditReport;
int ExitLift;
int a;
UseLift = 1;
AuditReport = 2;
ExitLift = 3;
}
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner d = new Scanner(System.in);
int a = d.nextInt();
Scanner kb = new Scanner(System.in);
// array containing usernames
String[] name = {"barry", "matty", "olly", "joey"}; // elements in array
if (a == 1) {
System.out.println(" Enter your name ");
}
String name1 = kb.nextLine();
boolean b = true;
int j = 0;// counter will start at 0
outerloop:
while (j < 3) {
System.out.println("Enter your name");
}
for (int i = 0; i < name.length; i++) {
if (name[i].equals(name1)) {
System.out.println("you are verified you may use the lift, calling lift ");
}
break;// to stop loop checking names
}
System.out.println("Username Invalid");
j++;
if (a == 2) {
System.out.println("");
}
if (a == 3) {
System.out.println(" Please Exit Lift ");
}
}
}
here you go:
public static void main(String... args) {
String[] verifiedNames = { "barry", "matty", "olly", "joey" };
System.out.println("choose an option");
System.out.println("Uselift(1)");
System.out.println("see audit report(2)");
System.out.println("Exit Lift(3)");
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1:
scanner.nextLine(); // get '\n' symbol from previous input
int nameAttemptsLeft = 3;
while (nameAttemptsLeft-- > 0) {
System.out.println(" Enter your name ");
String name = scanner.nextLine();
if (Arrays.asList(verifiedNames).contains(name)) {
System.out.println("dear " + name + " you are verified " +
"you may use the lift, calling lift ");
break; // break out of loop
}
}
if (nameAttemptsLeft < 0) {
System.out.println("Username Invalid");
}
break;
case 2:
System.out.println("option 2");
break;
case 3:
System.out.println(" Please Exit Lift ");
break;
}
scanner.close();
}
Your while loop below:
while (j < 3) {
System.out.println("Enter your name");
}
will loop forever since j is not incrementing (j++). I believe you've mis-matched your curly braces at some point.