Java 中的扫描仪不工作

发布于 2024-09-09 02:23:51 字数 1972 浏览 0 评论 0原文

我正在尝试编写一个非常简单的猜数字游戏(代码如下)。一轮结束后,用户应该能够决定是否要玩另一轮。问题是,程序总是跳过最后一个问题(永远不要让用户回答“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();
    }
}

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天煞孤星 2024-09-16 02:23:51

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

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

下面是重现该行为的最小代码片段:

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

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

nextInt() = 5
nextLine() = 

nextLine()< /code> 没有阻止您的输入,因为当前行仍然有一个空字符串。

作为比较,当您输入时,输入 5 yes!,然后按 Enter,则输出为:

nextInt() = 5
nextLine() =  yeah!

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

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


在半开范围上

假设要猜测的数字在 1 到 10 之间(含 1 和 10),则以下代码是“错误的”:

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

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

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

即像 Java 的 API 中的很多方法一样,< code>Random.nextInt(int) 使用半开范围,包含下限和排除上限。

相关问题

Use want = scan.next(); instead of 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.

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:

nextInt() = 5
nextLine() = 

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

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

nextInt() = 5
nextLine() =  yeah!

Note that " yeah!" actually comes from the same line as the 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. 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":

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:

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

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.

Related questions

别理我 2024-09-16 02:23:51

使用 scan.next()+ scan.nextLine(); 代替
例如。

Scanner scan = new Scanner(System.in);

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

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

Use 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).
So, when you use next it goes to the next token, then you can get the remaining input using nextLine()

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文