简体   繁体   English

Java 中的扫描仪不起作用

[英]Scanner in Java not working

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.Scanner I 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();
    }
}

Use want = scan.next();使用want = scan.next(); instead of nextLine() .而不是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, 5 and 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!为了比较,当您输入时,请说5 yeah! and then hit Enter , then the output is:然后按 Enter ,则输出为:

nextInt() = 5
nextLine() =  yeah!

Note that " yeah!"请注意" yeah!" actually comes from the same line as the 5 .实际上与5来自同一行。 This is exactly as specified in the documentation:这完全符合文档中的规定:

String nextLine() : Advances this scanner past the current line and returns the input that was skipped. String nextLine() :将此扫描器String nextLine()到当前行并返回被跳过的输入。 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.位置设置为下一行的开头。


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相关问题

Use scan.next()+ scan.nextLine();使用scan.next()+ scan.nextLine(); instead eg.相反,例如。

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).出现问题是因为输入的最后一行的最后一个换行符仍在输入缓冲区中排队,而下一个nextLine()将读取该行的其余部分(这是空的)。 So, when you use next it goes to the next token, then you can get the remaining input using nextLine()因此,当您使用 next 时,它会转到下一个标记,然后您可以使用nextLine()获取剩余的输入

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

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