Exception in thread "main" java.util.NoSuchElementException caused by a Scanner [duplicate] - java

This question already has answers here:
java.util.NoSuchElementException - Scanner reading user input
(5 answers)
Closed 3 years ago.
I m new, please have patience with me :)
I m not figure out why this method it s not working properly. It is creating me the account but, when the account was successfully created, it s not running well on the same method mainMenu(). I used a recursive call of the same method....
In the debug seems that it s not something well with my scanner from the second call of the method.
I m a Student
public void mainMenu() {
System.out.println("Select your option: ");
System.out.println("1. Open a new account");
System.out.println("2. Display all accounts");
System.out.println("If you want to logout press 9");
Scanner sc = new Scanner(System.in);
int option = 0;
do {
try {
option = sc.nextInt();
System.out.println();
switch (option) {
case 1:
accountUtil.openNewAccount(userConsoleUtil.getUser().getUserName());
mainMenu();
break;
case 9:
userConsoleUtil.logout();
displayLoginMenu();
break;
default:
System.out.println("Invalid option! Try again");
}
} catch (InputMismatchException e) {
System.out.println("Invalid option! Try again");
}
sc.nextLine();
} while (option != 9);
sc.close();
}
if the object account was created, it should return to beginning of the method, allowing to create a new account or exit with logout

It feels like you mistakenly wrote sc.nextLine() which takes an input from the user.
After the the end of catch block the line sc.nextLine() might give you unexpected output

Given your current code and the comments, it looks like you're creating scanners in your other methods and closing them. Don't do that. When you close the scanner, you also close System.in, leading to a NoSuchElementException.
Read this

Related

Java: how to reject incorrect input and wait for proper input using Scanner

This is the basic setup for a little console-based quiz game. The answers are numbered. I want the player to give the answer number. If the input is not a number, then my program should give a warning, and wait for proper input.
Instead, what I get (after inserting something that is not a number) is an infinite loop of asking the question and presenting the answers again.
public static void main(String[] args) {
boolean quizActive = true;
while(quizActive) {
presentQuestion();
presentAnswers();
Scanner s = new Scanner(System.in);
if (s.hasNext()) {
String choice = s.next();
if (!NumberUtils.isNumber(choice)) {
presentText("Please insert the answer number.");
} else {
System.out.println("You made a choice!");
checkAnswer(choice);
quizActive = false;
}
s.close();
}
}
}
What am I doing wrong here?
If you do not want to question and answers be presented each time move presentQuestion() and presentAnswers() outside the loop.
But main problem is that you closing Scanner.
Remove s.close(); and move Scanner s = new Scanner(System.in); outside of the loop.
I really don't get the point in using scanner for acquiring user input.
The scanner class is perfect to process structured input from a flat file with known structure like an CSV.
But user input need to deal with all the human imperfection. After all the only advantage you get is not needing to call Integer.parseInt() your yourself at the cost to deal with the not cleared input when scanne.nextInt() fails...
So why not using InputStreamReader aside with a loop suggested by others?
Here an Example :
public class Application {
public static void main(String [] args) {
System.out.println("Please insert the answer number. ");
while (true) {
try {
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
System.out.println("You made a choice!");
checkAnswer(choice);
break;
} catch (Exception e) {
System.out.println("Invalid Number, Please insert the answer number ");
}
}
}
}
You started your Quiz in a loop which is regulated by your quizActive boolean. That means that your methods presentQuestion() and presentAnswers() get called every time the loop starts again.
If you don't input a number but a character for example, your program will run the presentText("Please insert the answer number.") and start the loop again. As it starts the loop again, it will call the methods presentQuestion() and presentAnswers().
To stop that, you can do another loop around the input-sequence. Also your Scanner s = new Scanner(System.in) should be outside the loop. And you shouldn't close your Scanner right after the first input and then open it again!
if you want a code example, please tell me :)

Infinite Loop in My Exception Handling? [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
I'm trying to validate a user's input on a menu. Options are 1, 2, 3, and 4. I'm trying to handle the InputMismatchException error when they enter in a letter. I can't see what I'm doing wrong to make my code get stuck in an infinite loop.
System.out.println("What will be your starting balance?");
double startingBalance =0;
boolean check = false;
while(!check) {
try {
startingBalance = input.nextDouble();
check = true;
}
catch (InputMismatchException e) {
System.out.println("Invalid input!");
//startingBalance = 0;
//e.printStackTrace();
//check = false;
}
}
It looks like it get into the catch part, but loops through that repeatedly instead of going back to the try. I tried doing input.nextDouble();
to clear input buffer, but did nothing. Any help would be greatly appreciated.
You can use input.nextLine(); to clear your Scanner in your catch block:
while (!check) {
try {
startingBalance = input.nextDouble();
check = true;
} catch (InputMismatchException e) {
System.out.println("Invalid input!");
input.nextLine();//this will clear your Scanner and repeat again
}
}
Can I ask why you used nextLine() as opposed to nextDouble() ?
because nextLine move the Scanner to the next line
you need to set boolean check = false after first check and also use input.nestLine()

Scanner throwing NoSuchElementException on the second time of .nextInt(); [duplicate]

This question already has answers here:
Scanner throws NoSuchElementException on nextInt
(2 answers)
Closed 6 years ago.
The first time menu() is displayed, I'm able to enter input and runGame() works. The second time the menu is displayed, the program is crashing on the line int answer = scanner.nextInt() with a java.util.NoSuchElementException. It seems that there isn't a 'nextInt' to read in, but I don't ever have the chance to enter it the second time.
public void runGame(){
int userPick = 0;
userPick = menu();
while (userPick != 10){ //user exists with a choice of 10
switch (userPick){
case 1:
System.out.println("User picked 1");
break;
case 2:
...
default:
...
}
userPick = menu();
}
public int menu(){
Scanner scanner = new Scanner(System.in);
System.out.println("Please choose an integer from 0 - 10(quit)");
int answer = scanner.nextInt();
scanner.close();
return answer;
}
Per, Scanner throws NoSuchElementException on nextInt
When you call scanner.close() it closes your underlying stream, which is System.in; once you close System.in the only way to get it back is to restart your program.
Removing the close took care of the issue.

try/catch infinite loop? [duplicate]

This question already has answers here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
(5 answers)
Closed 5 years ago.
Help, I am completely new to java and I am trying to create a loop that will ask for an input from the user which is to be a number. If the user enters anything other than a number I want to catch the exception and try again to get the correct input. I did this with a while loop however it does not give the opportunity after the error for the user to type in anything it loops everything else but that. Please help me to see understand what is wrong and the correct way to do this... Thank you. This is what I have:
import java.util.Scanner;
import java.util.InputMismatchException;
public class simpleExpressions {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
while ( true ) {
double numOne;
System.out.println("Enter an Expression ");
try {
numOne = keyboard.nextInt();
break;
} catch (Exception E) {
System.out.println("Please input a number only!");
} //end catch
} //end while
} //end main
while ( true )
{
double numOne;
System.out.println("Enter an Expression ");
try {
numOne = keyboard.nextInt();
break;
}
catch (Exception E) {
System.out.println("Please input a number only!");
}
This suffers from several problems:
numOne hasn't been initialized in advance, so it will not be definitely assigned after the try-catch, so you won't be able to refer to it;
if you plan to use numOne after the loop, then you must declare it outside the loop's scope;
(your immediate problem) after an exception you don't call scanner.next() therefore you never consume the invalid token which didn't parse into an int. This makes your code enter an infinite loop upon first encountering invalid input.
Use keyboard.next(); or keyboard.nextLine() in the catch clause to consume invalid token that was left from nextInt.
When InputMismatchException is thrown Scanner is not moving to next token. Instead it gives us opportunity to handle that token using different, more appropriate method like: nextLong(), nextDouble(), nextBoolean().
But if you want to move to other token you need to let scanner read it without problems. To do so use method which can accept any data, like next() or nextLine(). Without it invalid token will not be consumed and in another iteration nextInt() will again try to handle same data throwing again InputMismatchException, causing the infinite loop.
See #MarkoTopolnik answer for details about other problems in your code.
You probably want to use a do...while loop in this case, because you always want to execute the code in the loop at least once.
int numOne;
boolean inputInvalid = true;
do {
System.out.println("Enter an expression.");
try {
numOne = keyboard.nextInt();
inputInvalid = false;
} catch (InputMismatchException ime) {
System.out.println("Please input a number only!");
keyboard.next(); // consume invalid token
}
} while(inputInvalid);
System.out.println("Number entered is " + numOne);
If an exception is thrown then the value of inputInvalid remains true and the loop keeps going around. If an exception is not thrown then inputInvalid becomes false and execution is allowed to leave the loop.
(Added a call to the Scanner next() method to consume the invalid token, based on the advice provided by other answers here.)

java, getting user input through scanner and system.in [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
how can I give a condition on an input from "system.in" that will halt the program until the right value is inserted?
for exemple, I'm waiting for an INT from the user, 1,2,3,4 or 5
the user inputs "hello"
how can i give the user a message of "Invalid input, try again"
and keep the program at halt until he does give the right one?
update: I didnt came so you can write my code, right now it looks something like this:
int j=UserIn.nextInt();
switch (j) {
case 1:
break;
case 2:
writetoDic(word, "dict.txt");
break;
case 3:
word = correction;
break;
i'm asking that, if im getiing something else than an int from the user, how can i ask the user to give a valid argument instead of just getting an error?
You need to use a loop. I don't think you actually mean halt the program, but actually preventing to program to proceed until valid input. You can do something like this
Scanner scanner = new Scanner(System.in);
int num;
while (true) {
try {
System.out.println("Enter a number: ");
num = scanner.nextInt();
if (num >= 1 && num <= 5) {
break;
}
} catch (InputMistmatchException ex){
System.err.println("Input needs to be a number between 1 and 5, dummy.");
}
}
Program will run if not between 1 and 5 and not an integer

Categories

Resources