[英]Scanner in Java not working
我正在尝试编写一个非常简单的猜数字游戏(代码如下)。 一轮结束后,用户应该能够决定他/她是否想再玩一轮。 问题是,程序总是跳过最后一个问题(从不让用户回答“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()
:将此扫描器String nextLine()
到当前行并返回被跳过的输入。 此方法返回当前行的其余部分,不包括末尾的任何行分隔符。 位置设置为下一行的开头。
假设要猜测的数字介于 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 中的很多方法一样, Random.nextInt(int)
使用半开范围,包含下限和排除上限。
使用scan.next()+ scan.nextLine();
相反,例如。
Scanner scan = new Scanner(System.in);
String s = scan.nextLine() +scan.nextLine();
出现问题是因为输入的最后一行的最后一个换行符仍在输入缓冲区中排队,而下一个nextLine()
将读取该行的其余部分(这是空的)。 因此,当您使用 next 时,它会转到下一个标记,然后您可以使用nextLine()
获取剩余的输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.