At java base java util scanner nextint scanner java 2212

java.util.NoSuchElementExeption regarding the Scanner class?

The basis of this program is to have a menu that leads to various different «lessons» that need to be completed. The toMenu() method runs and returns a value back to the main method correctly, and the beginning text of the method3_13() that states «Please enter a positive integer below: «, but after that an error message is displayed. This is the error message:

Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2212) at Chapter3ShortAnswers.method3_13(Chapter3ShortAnswers.java:67) at Chapter3ShortAnswers.main(Chapter3ShortAnswers.java:15) 
import java.util.Scanner; public class Chapter3ShortAnswers < public static void main(String []args) < int lesson = toMenu(); //takes user to menu and returns user-inputted value switch (lesson) < // switch statement that leads the user to each method's lesson case 0: System.out.println("Thank you for running this program! Have a great day!"); case 1: method3_13(); case 2: case 3: case 4: case 5: case 6: case 7: case 8: >> /** * FINSH THIS AT THE END * pre: none * post: returns number to lesson * while: accept user input number */ public static int toMenu() < Scanner input = new Scanner(System.in); int chapterNum; System.out.println("Table of Contents . Please type the number adjacent to the Lesson you would like to visit \n(Press 0 to go back to the menu, press 0 again to end the program): \n"); System.out.format("%-10s %8s", "Lesson", "Input Number\n"); // each lesson has a respective number the user // this is the number the user inputs System.out.format("%-10s %8s", "3.13", "1\n"); System.out.format("%-10s %8s", "3.14", "2\n"); System.out.format("%-10s %8s", "3.15", "3\n"); System.out.format("%-10s %8s", "3.16", "4\n"); System.out.format("%-10s %8s", "3.18", "5\n"); System.out.format("%-10s %8s", "3.19", "6\n"); System.out.format("%-10s %8s", "3.20", "7\n"); System.out.format("%-10s %8s", "3.21", "8\n"); System.out.println("\nType your number here: "); chapterNum = input.nextInt(); input.close(); return chapterNum; // returns the user inputed number back to the main menu, which assigns it to variable "lesson" >/** * */ public static void method3_13() < int chapterNum = 0; int user; Scanner input = new Scanner(System.in); System.out.println("Please enter a positive integer below: "); user = input.nextInt(); if(user % 1 == 0 && user >= 0) < System.out.println("Thank you for entering a number! To go back to the menu and choose another lesson, press 0. "); >else < while (user % 1 != 0 || user < 0) < if(user % 1 != 0) < System.out.println("This is not an integer. Please try again with an integer."); >else if (user < 0) < System.out.println("This is not a positive ineger. Please try again with a positive integer"); >else if (user % 1 != 0 && user < 0) < System.out.println("This is not an integer, nor is it positive. Please try again with a positive integer."); >> if (user % 1 == 0) < System.out.println("Thank you for entering a number! To go back to the menu and choose another lesson, press 0."); chapterNum = input.nextInt(); if(chapterNum == 0) < toMenu(); >> > input.close(); > > 

Источник

Читайте также:  Php обрезать массив до определенной длины

Java exception in thread «main»

I made a simple program which generates a random number between 1 to 100 and asks the user to enter a number between 1 and 100. If the number is more than the random number a message is displayed saying that it is more than the random number and if it is less it displays the opposite. The user only has 10 chances to guess the correct number. Here is the code:

import java.util.Scanner; public class Program < public static void main(String[] args) < Scanner sc = new Scanner(System.in); int random_num = (int) (Math.random() * 100) + 1; System.out.println("guess a number between 1 and 100"); boolean isCorrect = false; for (int i = 1; i random_num) System.out.println("It is less than " + input); else if (input < random_num) System.out.println("It is more than " + input); else < isCorrect = true; break; >> if (isCorrect) System.out.println("Congragulation you have guessd the correct number i.e " + random_num); else System.out.println("Game over it was " + random_num); > > 
guess a number between 1 and 100 It is more than 10 Exception in thread "main" java.util.NoSuchElementException at java.base/ java.util.Scanner.throwFor(Scanner.java: 937) at java.base/ java.util.Scanner.next(Scanner.java: 1594) at java.base/ java.util.Scanner.nextInt(Scanner.java: 2258) at java.base/ java.util.Scanner.nextInt(Scanner.java: 2212) at Program.main(Program.java:15) 

3 Answers 3

You are looping over the Scanner , but not checking if you have any input to fetch.

Here is an excerpt from the Java docs:

public int nextInt()

Scans the next token of the input as an int.

An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.

Returns:

the int scanned from the input

InputMismatchException — if the next token does not match the Integer regular expression,
or is out of range
NoSuchElementException — if input is exhausted
IllegalStateException — if this scanner is closed

Your code is valid for a standard Java environment.
However since you run the code in the SoloLearn Java container, you run into an error case that normally shouldn’t happen. Which is another thread already closed the input stream.

As Ivar already mentioned, you simply need to change your code to this to make it work on SoloLearn without errors:

But since SoloLearn’s implementation needs you to feed all of your input at once (different inputs seperated by a line break), you won’t be able to run this correctly with different guesses.

SoloLearn will take those inputs, seperated by line breaks, and reads the different lines one at a time.
Then returns the inputs one at a time to your program.
Once it has no more input, it will close the stream.
However your program still tries to read this stream and then gets a java.util.NoSuchElementException error.

Here is reproducable code of the error with wath I believe happens behind the scenes at SoloLearn:

import java.io.ByteArrayInputStream; import java.util.Scanner; public class Program < private String[] userInput; private int inputNumber; public Program(String input) < this.userInput = input.split(" "); this.inputNumber = 0; >public void startGame() < int random_num = (int)(Math.random()*100)+1; System.out.println("Guess the number between 1 and 100!"); boolean isCorrect = false; for (int i = 1; i random_num) System.out.println("It is less than " + input); else if (input < random_num) System.out.println("It is more than " + input); else < isCorrect = true; break; >> if(isCorrect) System.out.println("Congratulations, you have guessed the correct number i.e " + random_num); else System.out.println("Game over! The number was " + random_num); > private int getInput() < if (inputNumber < userInput.length) fakeUserInput(); Scanner sc = new Scanner(System.in); int input = -1; input = sc.nextInt(); if (inputNumber == userInput.length) sc.close(); return input; >private void fakeUserInput() < System.setIn(new ByteArrayInputStream(userInput[inputNumber].getBytes())); inputNumber++; >public static void main(String[] args) < Program p = new Program("10 20 30"); p.startGame(); >> 

We feed it 3 guesses: 10, 20 and 30

Guess the number between 1 and 100!
Guess 1: It is more than 10
Guess 2: It is more than 20
Guess 3: It is more than 30
Guess 4: Exception in thread «main» java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:873)
at java.util.Scanner.next(Scanner.java:1496)
at java.util.Scanner.nextInt(Scanner.java:2128)
at java.util.Scanner.nextInt(Scanner.java:2087)
at Program.getInput(Program.java:47)
at Program.startGame(Program.java:24)
at Program.main(Program.java:62)

As you can see, once the inputs are depleted and the stream is closed, we get this error.

I hope this explains your problem and sheds some light on the WHY.

Источник

How to take input in java where array length is not defined?

Hint: have you debugged through the code? How far does it get? When do you expect hasNextLine() to return false?

I would suggest just reading the first line as a whole, then splitting it on spaces and parsing each part separately. Scanner is remarkably hard to use «properly».

2 Answers 2

The reason you are seeing java.util.InputMismatchException is because you provided input «Alice» to the statement sc.nextInt() , and the scanner is telling you that it doesn’t know how to convert a java.lang.String input to an int (which is the return type of nextInt() ).

Here’s a very simple example that reproduces the same behavior:

Scanner sc = new Scanner(System.in); int x = sc.nextInt(); 

If you run those two lines and enter a non-integer, like «d», it will throw an exception:

d Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2212) at a91.main(a91.java:6) 

To fix it, you need to replace nextInt() with something that is tolerant of non-numeric input, possibly nextLine() . Here is a (very) simple example showing how that could work. Note this is just highlighting the behavior you’re asking about, namely: how to address InputMismatchException . As with your original program, there is no loop termination – it will run forever (until you quit the program).

Scanner sc = new Scanner(System.in); int x = sc.nextInt(); while (sc.hasNext()) < String s = sc.nextLine(); System.out.println("got this: " + s); >1 2 3 4 5 6 got this: 2 3 4 5 6 Alice got this: Alice 

Источник

java.util.NoSuchElementException in basic Scanner usage

I want to take an input from user with using Scanner in my project. It gives same error so i created another project to try Scanner only but it still gives this error. I looked up for solved questions in stackoverflow but they’re large codes than mine, so maybe NoSuchElementException caused by their codes. I mean isn’t it weird in simple Scanner code? Simpler codes are using in Scanner tutorials. Am i doing little thing wrong? Here it is:

package deneme; import java.util.Scanner; public class Main < public static void main(String[] args) < Scanner input = new Scanner(System.in); int number1 = input.nextInt(); >> 
JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64" cd /home/frogwine/NetBeansProjects/deneme; /home/frogwine/.gradle/wrapper/dists/gradle-4.10.2-bin/cghg6c4gf4vkiutgsab8yrnwv/gradle-4.10.2/bin/gradle --configure-on-demand -x check run Configuration on demand is an incubating feature. > Task :compileJava UP-TO-DATE > Task :processResources NO-SOURCE > Task :classes UP-TO-DATE > Task :run FAILED Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.Scanner.throwFor(Scanner.java:937) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2212) at deneme.Main.main(Main.java:20) FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':run'. > Process 'command '/usr/lib/jvm/java-11-openjdk-amd64/bin/java'' finished with non-zero exit value 1 * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 1s 2 actionable tasks: 1 executed, 1 up-to-date 
Product Version: Apache NetBeans IDE 11.0 (Build incubator-netbeans-release-404-on-20190319) Updates: Updates available Java: 11.0.4; OpenJDK 64-Bit Server VM 11.0.4+11-post-Debian-1deb10u1 Runtime: OpenJDK Runtime Environment 11.0.4+11-post-Debian-1deb10u1 System: Linux version 4.19.0-6-amd64 running on amd64; UTF-8; en_US (nb) User directory: /home/frogwine/.netbeans/11.0 Cache directory: /home/frogwine/.cache/netbeans/11.0 

Источник

Оцените статью