This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
do
{
// asking user choices
choice = Integer.parseInt(br.readLine());
switch(choice)
{
// doing something
}
System.out.println("Do you want to continue?");
System.out.println("(Y/N)");
ans = (char) br.read();
}
while(ans == 'y' || ans == 'Y');
I am using eclipse;
I want to check whether the user want to re-enter the switch case by entering his answer by a char 'y' || 'Y'.
But whenever i enter the char 'Y' it enters the do loop but also executes the choice variable. And as the choice variable is int; it throws number format exception.
Do you want to continue?
(Y/N)
y
// prints all my switch options
Exception in thread "main":
java.lang.NumberFormatException: For input string: ""
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at ArithemeticOperations.main(ArithemeticOperations.java:45)
See that "input string" part of the message? It tells you that the input to the parseInt function is empty. And it's empty because it's the newline after you entered your y. You need to read a whole line for the "continue" answer, and get the character from that full line.
#SomeProgrammerDude already explained the reason behind your problem. So, i am not repeating it. You can modify your code as given below.
String ans;
do{
// asking user choices
choice = Integer.parseInt(br.readLine());
switch(choice){
// doing something
}
System.out.println("Do you want to continue?");
System.out.println("(Y/N)");
ans = br.readline();
}while(ans.toLowerCase().equals("y"));
Related
When using a switch case with integers, I am able to successfully stop the user from crashing the program with a try/catch when they enter a letter (a, b, c, etc, not case specific). However, I can only stop it after an integer is entered. For this example, it is NOT my actual code, it is only an example as it is a general question. Secondly, I want to try and get it working with suggestions, not having it done for me:
int choice
Scanner scan = new Scanner (System.in);
System.out.println ("Enter a number");
System.out.println ("1: Example one");
System.out.println ("2: Example two");
System.out.println ("0: Exit");
choice = scan.nextInt();
Loop: for (;;)
{
switch (choice)
case 1: System.out.println ("Example one successful");
choice = scan.nextInt();
break;
case 2: System.out.println ("Example two successful");
choice = scan.nextInt();
break;
case 0: System.exit (0);
break Loop;
default: try
{
System.out.println ("Please enter a number")
choice = scan.nextInt();
}
catch (InputMismatchException error)
{
System.out.println ("Not a valid number: " + error);
choice = scan.nextInt();
}
If the user enters a "1", it outputs the proper text inside the case 1 block. The same goes for case 2 and case 0 to exit. It will loop properly and continuously like this:
Enter a number: 1
Example one successful
Enter a number: 1
Example one successful
Enter a number: 2
Example two successful
Enter a number: ghdrf
Not a valid number: java.util.InputMismatchException
Enter a number: 0
The try/catch works in catching the wrong input, all the other case work. The problem is if the user never enters an integer from the start and enters a letter instead. It will throw the InputMismatchException right away. The try/catch doesn't even try to catch it.
My thinking was because I assigned the scanner to read an integer from the start. I tried to start there. I originally tried this between the loop label and the switch statement as it is the only place I could put it to not get an error:
Loop: for (;;)
{
String letter = input.nextLine();
if(letter.matches("[1-9]*")
{
choice = Integer.valueOf(letter);
}
else
{
System.out.println("Invalid input");
}
switch (choice)
...
This worked somewhat in the same way as my try/catch except it was simply printing "invalid input" with each selection (because of my print statement, I know that). But the same problem was occurring. If a letter was input instead of an integer right off the bat, it would throw an InputMismatchException. I have a feeling it has something to do with what is in the scanner. I've tried experimenting with "next(), nextLine(), nextInt(), equals()" and I've tried parsing with "Integer.valueOf()" trying to get the current line in the scanner to check it or parse it.
This leads me to my questions:
Am I correct to assume that the scanner is reading the input and throwing the exception before I have a chance to catch it?
How do I read the first line in the scanner at the beginning of the program in order to check if it is an integer or a String? I'm not a big fan of skipping the first line because then it causes the user to have to input their number twice in order for the program to print out a message such as:
Enter a number: 1
Enter a number: 1
Example one successful
Any input is greatly appreciated, thank you!
Question #1: no. The problem is, that the exception occurs in those lines which are not surrounded by try-catch (e. g. before the loop, in case 1 or case 2).
Question #2: to read a line, use Scanner#nexLine(). There's no need to have the user to perform his input twice.
Hint: write a method that requests an int value from the user and that returns only, if he entered a correct value.
You have 2 calls to next int. You're only catching exceptions from one of them. You need to do it for both.
I'd put some thought into reorganizing this code a bit. You don't really need two calls to nextInt. You can do it with one by changing what things are in the loop and what aren't. Since you're a beginner I'll let you think about that for a bit rather than hand you the answer.
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 4 years ago.
I'm writing a very simple program and where I am getting 3 ints from a user and want to check to make sure they are all ints before storing them into seperate variables to process. The check I've used works on the first input but fails and throws the exception on the second two.
boolean properInt = scanner.hasNextInt();
int largest = Integer.MAX_VALUE;
boolean anError = false;
while(properInt=false){
anError=true;
System.out.println("Invalid number...whole numeric values only");
}
while(properInt =true){
int a= scanner.nextInt();
System.out.println("you entered "+ a);
int b = scanner.nextInt();
System.out.println("you entered "+ b);
int c= scanner.nextInt();
System.out.println("you entered "+ c);
}
Reason is when you use any of the nextXxx(...), the scanner cursor is reset to where it was before the call. When you press 'enter' key after entering a valid number, scanner ignores the 'character' (enter). However, when you enter an invalid value, an exception is thrown and the enter key character is seen by the next 'nextInt' as another condition and so won't work.
I would suggest using nextLine and then Integer.ParseInt and catching NumberFormatException.
Also, your while loop check is incorrect.
properInt=false is a statement.
while(properInt==false) is a condition..
English is not my strength so if its confusing let me know.
This question already has an answer here:
Exception handling infinite loop
(1 answer)
Closed 5 years ago.
This is a part of my code which is used to validate an input and loop if it is a character, however it causes an infinite loop when a character is input, but works fine when an integer is used. I don't know whats causing the infinite loop but any help would be appreciated.
System.out.println("Please type in a mark and enter -1 to end the program");
while (mark != -1) {
if (in.hasNextInt()) {
mark = in.nextInt();
}
else {
System.out.println("Please input an integer: ");
}
If you input a character the:
if (in.hasNextInt())
Will return false, and you go to the else, when it loops, the in.hasNextInt() is still false entering the else and looping forever.
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I have a scanner that gets a users input x which if input correctly outputs "correct" and if the input is not right, it will output "incorrect". However whether i type the correct or incorrect string im stuck in an endless loop of the while loop outputting "incorrect".
How can i check if a users input is correct and if so, output the word "correct" and move onto the next part of the program. If the input is incorrect, output "incorrect" and repeat the loop until the input is correct.
Hopefully this makes sense!
Code:
Scanner sc = new Scanner(System.in);
int n = 0;
String x = sc.nextLine();
while(n == 0){
if (x == "inv"){
System.out.println("correct");
n++;
}else{
System.out.println("incorrect");
}
}
I needed to use x.equals("Inv") rather than x == "Inv"
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I have this piece of code that is supposed to add String values to an arrayList through the Scanner's next() or nextLine() method. The problem with next() is that it ignores everything after the first white space so I get that I should use the nextLine() method instead. The problem with nextLine() is that that it doesn't record the input, instead it stores a couple of blank spaces into the arrayList. Here's the code:
System.out.println("\nWhat is your idea? ");
String i = in.nextLine();
in.nextLine();
meals.add(i);
System.out.println("\n" + i + " has been entered into the idea pool. \n");
System.in.read();
I added the extra "in.nextLine()" after the initial "String i = in.nextLine()" because that's the only fix I found when I researched this problem but it doesn't work for me, it just still just stores a couple of blank spaces. Also, the System.in.read(); at the end there is only there so that it doesn't just jump forward after taking the input.
Here is the code where the above sample fits into:
ArrayList<String> meals = new ArrayList<String>();
String select = "";
while(!select.equals("")){
System.out.println("What would you like to do?");
System.out.println("1. <Irrelevant>");
System.out.println("2. Enter an idea");
System.out.println("3. <Irrelevant>");
System.out.println("4. <Irrelevant>");
System.out.println("Q. <Irrelevant>");
select = in.next();
switch(select){
case "1":
//Some stuff here.
case "2":
//Here's where the above problem fits into.
case "3":
//More stuff here
//and so on...
}
}
The reason why you are facing such issue is because you are using firstly next() method to read the input, and the further inputs you are taking using nextLine().
next() accepts the input, and the input pointer stays on the same line as of the current input.
So, as soon as you enter your choice and hit Enter, the choice is saved into the select variable, but, the input pointer is still on the same line. You should use a nextLine() to move the pointer to a new line.
Then you should use any number of nextLine()'s to receive multiple lines.
Also, remove an extra nextLine() method call from the case 2 statement. Remove the System.in.read() too, as your problem would have been solved.
ArrayList<String> meals = new ArrayList<String>();
String select = "";
while(!select.equals("")){
System.out.println("What would you like to do?");
System.out.println("1. <Irrelevant>");
System.out.println("2. Enter an idea");
System.out.println("3. <Irrelevant>");
System.out.println("4. <Irrelevant>");
System.out.println("Q. <Irrelevant>");
select = in.next();
in.nextLine(); // add this extra line in your code
switch(select){
case "1":
//Some stuff here.
case "2":
System.out.println("\nWhat is your idea? ");
String i = in.nextLine();
meals.add(i);
System.out.println("\n" + i + " has been entered into the idea pool. \n");
case "3":
//More stuff here
//and so on...
}