gpt4 book ai didi

java - Java 中的扫描器不工作

转载 作者:搜寻专家 更新时间:2023-11-01 01:14:52 26 4
gpt4 key购买 nike

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

最佳答案

使用 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() 没有阻止您的输入,因为当前行仍然有一个空字符串。

为了比较,当你输入时,说 5 yeah! 然后按 Enter,然后输出是:

nextInt() = 5
nextLine() = yeah!

请注意 “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.


关于半开范围

假设要猜的数字在 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): Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)

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

相关问题

关于java - Java 中的扫描器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3236830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com