为什么这个程序在收到输入public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int numberDrawn = drawNumber();
int number;
System.out.println("Guess a number: ");
number = Integer.parseInt(reader.nextLine());
while (number != numberDrawn) {
if(number < numberDrawn) {
System.out.println("The number is greater");
} else if (number > numberDrawn) {
System.out.println("The number is lesser");
} else {
System.out.println("Congratulations, your guess is correct!");
}
}
}
private static int drawNumber() {
return new Random().nextInt(101);
}
后会创建无限循环?
$ sed 's/\([A-Z]\)/ \1/g' input.txt > output.txt
答案 0 :(得分:1)
您的核心代码如下:
int numberDrawn = new Random().nextInt(101);
int number = Integer.parseInt(reader.nextLine());
while (number != numberDrawn) {
...
}
但是在循环内部,您执行不更改 numberDrawn
或用户猜测number
。
因此while循环执行内部的内容(某些print语句),然后再次检查条件number != numberDrawn
。但由于数字没有变化,如果它们首先不相等,则进入下一次迭代。这显然持续不断地。
一个带数字的小例子:
int numberDrawn = 3;
int number = 10;
while (number != numberDrawn) {
...
}
现在number != numberDrawn
解析为3 != 10
true
,因此循环开始并执行打印:
if(number < numberDrawn) {
System.out.println("The number is greater");
} else if (number > numberDrawn) {
System.out.println("The number is lesser");
} else {
System.out.println("Congratulations, your guess is correct!");
}
自The number is greater
起打印3 < 10
。迭代结束并再次检查number != numberDrawn
。由于数字没有变化,它会再次解析为3 != 10
,即true
,继续无休止地。
如果数字不相等,你可能想重复猜谜游戏。为此,你需要移动猜测程序在循环中,如下所示:
int numberDrawn = drawNumber();
// Initial value which ensures that loop is entered
int number = -1;
while (number != numberDrawn) {
// Let the user guess a number
System.out.println("Guess a number!");
number = Integer.parseInt(reader.nextLine());
// Check the number
if(number < numberDrawn) {
System.out.println("The number is greater");
} else if (number > numberDrawn) {
System.out.println("The number is lesser");
} else {
System.out.println("Congratulations, your guess is correct!");
}
}
现在,您让用户根据上次迭代的消息重复选择新号码。
当然,您也可以使用do-while
循环而不是常规while
,然后-1
的初始number
值不需要。
答案 1 :(得分:0)
您打印出数字少于或大于但未在后面输入任何内容的声明,因此number
的值永远不会改变。尝试类似:
while (number != numberDrawn) {
if(number < numberDrawn) {
System.out.println("The number is greater");
number = Integer.parseInt(reader.nextLine());
} else if (number > numberDrawn) {
System.out.println("The number is lesser");
number = Integer.parseInt(reader.nextLine());
}
}
System.out.println("Congratulations, your guess is correct!");
答案 2 :(得分:0)
每次迭代后输入
number = Integer.parseInt(reader.nextLine());