简体   繁体   English

线程“main”中的Java异常

[英]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.我做了一个简单的程序,它生成一个 1 到 100 之间的随机数,并要求用户输入一个 1 到 100 之间的数字。如果该数字大于随机数,则会显示一条消息,说它大于随机数,并且如果它小于它显示相反。 The user only has 10 chances to guess the correct number.用户只有 10 次机会猜出正确的数字。 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.您正在遍历Scanner ,但不检查您是否有任何要获取的输入。

Here is an excerpt from the Java docs:以下是 Java 文档的摘录:

public int nextInt() public int nextInt()

Scans the next token of the input as an int.将输入的下一个标记扫描为 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.以 nextInt() 形式调用此方法的行为与调用 nextInt(radix) 完全相同,其中 radix 是此扫描器的默认基数。

Returns:返回:

the int scanned from the input从输入扫描的 int

Throws:抛出:

InputMismatchException - if the next token does not match the Integer regular expression, InputMismatchException - 如果下一个标记与 Integer 正则表达式不匹配,
or is out of range或超出范围
NoSuchElementException - if input is exhausted NoSuchElementException - 如果输入已用尽
IllegalStateException - if this scanner is closed IllegalStateException - 如果此扫描器已关闭

Spot your error message ;)发现你的错误信息 ;)


Your code is valid for a standard Java environment.您的代码适用于标准 Java 环境。
However since you run the code in the SoloLearn Java container, you run into an error case that normally shouldn't happen.但是,由于您在 SoloLearn Java 容器中运行代码,因此您会遇到通常不应该发生的错误情况。 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:正如 Ivar 已经提到的,您只需要将代码更改为此即可使其在 SoloLearn 上正常运行而不会出错:

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 的实现需要您一次提供所有输入(不同的输入由换行符分隔),您将无法使用不同的猜测正确运行它。

SoloLearn will take those inputs, seperated by line breaks, and reads the different lines one at a time. SoloLearn 将接受这些输入,由换行符分隔,并一次读取不同的行。
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.但是,您的程序仍会尝试读取此流,然后出现 java.util.NoSuchElementException 错误。

Here is reproducable code of the error with wath I believe happens behind the scenes at SoloLearn:这是我认为在 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我们给它 3 个猜测: 102030

And this is the output:这是输出:

Guess the number between 1 and 100!猜猜1到100之间的数字!
Guess 1: It is more than 10猜一:10多
Guess 2: It is more than 20猜2:20多
Guess 3: It is more than 30猜3:30多
Guess 4: Exception in thread "main" java.util.NoSuchElementException猜测 4:线程“main”中的异常 java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:873)在 java.util.Scanner.throwFor(Scanner.java:873)
at java.util.Scanner.next(Scanner.java:1496)在 java.util.Scanner.next(Scanner.java:1496)
at java.util.Scanner.nextInt(Scanner.java:2128)在 java.util.Scanner.nextInt(Scanner.java:2128)
at java.util.Scanner.nextInt(Scanner.java:2087)在 java.util.Scanner.nextInt(Scanner.java:2087)
at Program.getInput(Program.java:47)在 Program.getInput(Program.java:47)
at Program.startGame(Program.java:24)在 Program.startGame(Program.java:24)
at Program.main(Program.java:62)在 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().这是答案,我尝试这样做,并且在 main sc.close() 中找到了。 After comment line all work nice!注释行后一切正常! :

@I_code Is this the actual code you are using? @I_code 这是您使用的实际代码吗? It works fine for me.这对我来说可以。 That error is thrown when the the System.in is closed. System.in 关闭时会抛出该错误。 Are you using sc.close() somewhere that you didn't show in the code?您是否在代码中未显示的地方使用 sc.close() ?

– @Ivar Mar 15 '19 at 10:10 – @Ivar 2019 年 3 月 15 日 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.我对 Java 很陌生,所以我正在制作一个简单的程序,该程序输出一个数字的另一个数字的幂,其中两个数字都由用户输入。 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:早上好,您需要像这样初始化for之外的输入变量:

int input;

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

Try this and tell me试试这个然后告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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