Java 中的扫描仪不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3236830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:39:04  来源:igfitidea点击:

Scanner in Java not working

javainputjava.util.scanner

提问by bow

I'm trying to write a very simple number guessing game (code is below). After 1 round is finished, the user is supposed to be able to decide whether he/she wants to play another round or not. Problem is, the program always skips the last question (never letting the user answer 'y' or otherwise. What am I missing here? Is there something about java.util.ScannerI don't know about?

我正在尝试编写一个非常简单的猜数字游戏(代码如下)。一轮结束后,用户应该能够决定他/她是否想再玩一轮。问题是,程序总是跳过最后一个问题(从不让用户回答“y”或其他问题。我在这里错过了什么?有什么java.util.Scanner我不知道的吗?

import java.util.Random;
import java.util.Scanner;

public class GuessNum {

public GuessNum() {         

        int numRandom = 0;    
        int numGuess;    
        int life = 5;    
        String want = "";    
        Random rand = new Random();    
        Scanner scan = new Scanner(System.in);

        do {
            int lifeLeft = 5;
            numRandom = rand.nextInt(9)+1;

            System.out.print("\nGuess the Number [1..10]\n");
            System.out.print("===================\n");
            System.out.print("You have " + lifeLeft + " chances.\n");

            do {
                do {
                    System.out.print("What number do I have in mind: ");
                    numGuess = scan.nextInt();

                    if (numGuess < 1 || numGuess > 10)    
                        System.out.println("Invalid input. Range is 1-10.");    
                } while (numGuess < 1 || numGuess > 10);

                if (numGuess != numRandom && lifeLeft != 0)
                    System.out.println("Wrong! You only have " + --lifeLeft + " chances left.");

            } while (numGuess!=numRandom && lifeLeft > 0);

            if (numGuess == numRandom)
                System.out.println("Correct! -- in " + (life - lifeLeft) + " guess(es).");

            if (lifeLeft == 0) {
                System.out.println("You have no more lives..");
                System.out.println("This is the number: " + numRandom);
            }

            System.out.print("\nEnter 'y' if you want to play again or any other character to exit: ");
                want = scan.nextLine();
        } while (want.equals("y") || want.equals("Y"));
    }

    public static void main(String[] args) {            
        new GuessNum();
    }
}

采纳答案by polygenelubricants

Use want = scan.next();instead of nextLine().

使用want = scan.next();代替nextLine()

The reason for your problem is that following the preceding nextInt(), you're still on the same line, and nextLine()returns the rest of the current line.

您的问题的原因是在前面的之后nextInt(),您仍然在同一行上,并nextLine()返回当前行的其余部分。

Here's a smallest snippet to reproduce the behavior:

这是重现行为的最小片段:

Scanner sc = new Scanner(System.in);
System.out.println("nextInt() = " + sc.nextInt());
System.out.println("nextLine() = " + sc.nextLine());

When you type in, say, 5and then hit Enter, the output is:

当您输入时,例如,5然后按 Enter,输出为:

nextInt() = 5
nextLine() = 

That is, nextLine()did not block for your input, because the current line still has an empty string remaining.

也就是说,nextLine()没有阻止您的输入,因为当前行仍然有一个空字符串。

For comparison, when you type in, say 5 yeah!and then hit Enter, then the output is:

为了进行比较,当您输入时,说5 yeah!然后按 Enter,则输出为:

nextInt() = 5
nextLine() =  yeah!

Note that " yeah!"actually comes from the same line as the 5. This is exactly as specified in the documentation:

请注意," yeah!"实际上与5. 这完全符合文档中的规定:

String nextLine(): Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

String nextLine(): 将此扫描器推进到当前行并返回被跳过的输入。此方法返回当前行的其余部分,不包括末尾的任何行分隔符。位置设置为下一行的开头。



On half-open ranges

在半开范围内

Assuming that the number to guess is between 1 and 10 inclusive, the following code is "wrong":

假设要猜测的数字介于 1 和 10 之间,则以下代码是“错误的”:

numRandom = rand.nextInt(9)+1; // this can only be in 1..9 range inclusive!

Here's an excerpt from the documentation of java.util.Random:

这是文档的摘录java.util.Random

int nextInt(int n): Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

int nextInt(int n):返回一个伪随机的、均匀分布在 0(含)和指定值(不含)之间的 int 值

That is, like a lot of methods in Java's API, Random.nextInt(int)uses the half-open range, with inclusive lower bound and exclusive upper bound.

也就是说,就像Java的API中的很多方法一样,Random.nextInt(int)使用半开区间,包含下限和不包含上限。

Related questions

相关问题

回答by Navdeep Jha

Use scan.next()+ scan.nextLine();instead eg.

使用scan.next()+ scan.nextLine();,而不是如。

Scanner scan = new Scanner(System.in);

String s = scan.nextLine() +scan.nextLine();

Problem occurs because the last newline character for the last line of input is still queued in the input buffer and the next nextLine()will be reading the remainder of the line (which is empty). So, when you use next it goes to the next token, then you can get the remaining input using nextLine()

出现问题是因为输入的最后一行的最后一个换行符仍在输入缓冲区中排队,下一个nextLine()将读取该行的其余部分(这是空的)。因此,当您使用 next 时,它会转到下一个标记,然后您可以使用以下方法获取剩余的输入nextLine()