Java中的扫描仪无法正常工作

bow*_*bow 4 java input java.util.scanner

我正在尝试编写一个非常简单的猜数游戏(代码如下).在完成1轮之后,用户应该能够决定他/她是否想要进行另一轮比赛.问题是,程序总是跳过最后一个问题(永远不要让用户回答'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();
    }
}
Run Code Online (Sandbox Code Playgroud)

pol*_*nts 13

want = scan.next();而不是nextLine().

你的问题的原因是,按照前面的说法nextInt(),你仍然在同一行,并nextLine()返回当前行的其余部分.

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

Scanner sc = new Scanner(System.in);
System.out.println("nextInt() = " + sc.nextInt());
System.out.println("nextLine() = " + sc.nextLine());
Run Code Online (Sandbox Code Playgroud)

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

nextInt() = 5
nextLine() = 
Run Code Online (Sandbox Code Playgroud)

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

为了便于比较,当你键入,说5 yeah!然后打回车,然后输出为:

nextInt() = 5
nextLine() =  yeah!
Run Code Online (Sandbox Code Playgroud)

请注意," yeah!"实际上来自与...相同的行5.这与文档中指定的完全相同:

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


半开放范围

假设要猜测的数字在1到10之间(包括1和10),以下代码是"错误的":

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

以下是文档的摘录java.util.Random:

int nextInt(int n):返回伪随机,在0(包括)和指定值(不包括)之间均匀分布的int值

也就是说,像Java API中的许多方法一样,Random.nextInt(int)使用半开放范围,包含下限和独占上限.

相关问题