简体   繁体   中英

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 <= 10; i++) {
            int input = sc.nextInt();
            if (input > 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);
    }
}

But I get errors here is the output:

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) 

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

Throws:

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

Spot your error message ;)


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:

for (int i = 1; i <= 10 && sc.hasNextInt(); i++) {
    // Your logic
}

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 <= 10; i++) {
            System.out.print("Guess "+ i +": ");
            int input = getInput();
            if (input > 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

And this is the output:

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 .

here is answer, I try to do it and I found in main sc.close(). After comment line all work nice! :

@I_code Is this the actual code you are using? It works fine for me. That error is thrown when the the System.in is closed. Are you using sc.close() somewhere that you didn't show in the code?

– @Ivar Mar 15 '19 at 10:10

I'm having the same problem and it's so frustrating. I'm very new to Java so I was making a simple program that outputs a number to the power of another number with both numbers inputted by the user. This is my code:

import java.util.Scanner;
class Main {
    public static void main(String args[]) {
      Scanner input = new Scanner( System.in );
      int x = input.nextInt();
      int y = input.nextInt();
      int z = x;
      
      while (y > 1) {
          z = z * x;
          y = y - 1;
      };

      System.out.println(z);
    }
}

And this is the error that appears:

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 Main.main(Main.java:5)

Good morning you need to initialize the input variable outside the for like this:

int input;

for (int i = 1; i <= 10; i++) {
            input = sc.nextInt();
            if (input > random_num)

Try this and tell me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM