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

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.

Related

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

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

How to fix NoSuchElementException [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Close a Scanner linked to System.in
(5 answers)
Closed 4 years ago.
I had setup a method to check if the input matches the type int and doesn't return until it does.
It worked fine for a couple of projects so far but when I used it in my current one I got this kind of error when going into the method for the second time around.
Exception in thread "main" java.util.NoSuchElementException
Here is the method:
private static int inputHandler() {
Scanner sc = new Scanner(System.in);
int num = 0;
try{
System.out.println("Enter a number:");
num = sc.nextInt();
} catch(InputMismatchException e){
System.out.println("Input must match type int");
num = inputHandler();
}
sc.close();
return num;
}
If anyone knows how to fix this issue I would appreciate the help.

Scanner nextLine issue in Java [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
Just one question: why I must type answer = in.nextLine(); twice? If this line is single the program doesn't work as expected. Without second line the program doesn't ask you to enter a string.
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String answer = "Yes";
while (answer.equals("Yes")) {
System.out.println("Enter name and rating:");
String name = in.nextLine();
int rating = 0;
if (in.hasNextInt()) {
rating = in.nextInt();
} else {
System.out.println("Error. Exit.");
return;
}
System.out.println("Name: " + name);
System.out.println("Rating: " + rating);
ECTS ects = new ECTS();
rating = ects.checkRating(rating);
System.out.println("Enter \"Yes\" to continue: ");
answer = in.nextLine();
answer = in.nextLine();
}
System.out.println("Bye!");
in.close();
}
}
The Scanner-Object has an internal cache.
You start the scann for nextInt().
You press the key 1
You press the key 2
You press return
Now, the internal Cache has 3 characters and the scanner sees the third character(return) is not a number, so the nextInt() will only return the integer from the 1st and 2nd character (1,2=12).
nextInt() returns 12.
Unfortunately the return is still part of the Scanner's cache.
You call nextLine(), but the Method scans its cache for a newline-marker that has been kept in the cache from before the nextInt() call returned.
The nextLine() returns a 0-length-string.
The next nextLine() has an empty cache! It will wait until the cache has been filled with the next newline-marker.
reset()
There is a more elegant way to clear the cache instead of using nextLine():
in.reset();
Because you are using nextInt() this method only grabs the next int it doesn't consume the \n character so the next time you do nextLine() it finishes consuming that line then moves to the next line.

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

Confusin Error with Scanner

I keep getting this error and I do not know why :
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Daily.takingData(Daily.java:33)
at Daily.main(Daily.java:20)
this is my code:
import java.io.*;
import java.util.Scanner;
public class Daily
{
private static int size;
public static void main(String[] args) throws Exception {
System.out.println("Please enter amount of rows");
Scanner scan1 = new Scanner(System.in);
size = scan1.nextInt();
scan1.close();
System.out.println();
takingData(size);
}
public static void takingData(int rows) throws Exception {
System.out.println("Enter 1 To View Number of Markets");
System.out.println("Enter 2 To View Start and End Dates of Markets");
System.out.println("Enter 3 To View Start and End Dates of Contracts");
System.out.println("Enter 4 To View Averages of Markets");
System.out.println("Enter 0 To Quit Program");
int choice = 0;
Scanner scan2 = new Scanner(System.in);
choice = scan2.nextInt();
System.out.println("Got here");
scan2.close();
if (choice == 0)
System.exit(0);
}
}
My Out put is :
Enter 1 To View Number of Markets
Enter 2 To View Start and End Dates of Markets
Enter 3 To View Start and End Dates of Contracts
Enter 4 To View Averages of Markets
Enter 0 To Quit Program
(error here)
You are getting an error because you close your scanner right after you scan:
size = scan1.nextInt();
scan1.close();
and then try to scan again in takingData
remove the scan1.close(); that is outside of your takingData.
When you close a Scanner, the InputStream that it is scanning from is also closed, in this case your System.in is being closed.
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
Taken from Scanner javadocs
The problem is that you're closing the first instance of Scanner here
scan1.close();
which is closing the associated InputStream (System.in) - this prevents the second Scanner instance of reading from the stream.
Don't close the scanner. Also you could create a single instance of Scanner for reading all values.
From a design point of view I would move from static methods to an OO approach with the single Scanner instance created in the constructor of Daily and all methods becoming instance methods. This will help with testability of the Object.
public class Daily {
private final Scanner scanner;
public Daily() {
scanner = new Scanner(System.in);
}
public int getRows() {
System.out.println("Please enter amount of rows");
return scanner.nextInt();
}
public static void main(String[] args) throws Exception {
Daily daily = new Daily();
int rows = daily.getRows();
int mainOption = daily.getMainOption(rows);
switch (mainOption) {
case 0: // TODO: refactor to use enums
System.exit(0);
}
}
public int getMainOption(int rows) {
System.out.println("Enter 1 To View Number of Markets");
System.out.println("Enter 2 To View Start and End Dates of Markets");
System.out.println("Enter 3 To View Start and End Dates of Contracts");
System.out.println("Enter 4 To View Averages of Markets");
System.out.println("Enter 0 To Quit Program");
return scanner.nextInt();
}
}
The answer to your question is here: https://stackoverflow.com/a/13042296/1688441 for question:
java.util.NoSuchElementException - Scanner reading user input
I am quoting:
When you call, sc.close() in first method, it not only closes your
scanner but closes your System.in input stream as well. This you can
verify by printing its status at very top of the second method as :
System.out.println(System.in.available());
So now when you re-instantiate, Scanner in second method, it doesn't find any open
System.in stream and hence the exception.
Get rid of the initial int choice, and try this:
int choice = scan2.nextInt();
Shouldn't really make a difference, but it could help.

Categories

Resources