![](/img/trans.png)
[英]Infinite loop(?) when trying to use .hasNext() when reading from a file
[英]Infinite printing when trying to use a loop
编程新手。
我在Java中有一个类,正在尝试编写此程序,但它不停地打印,甚至还困扰着我的浏览器! (我正在使用在线ide)
我的指示:问:你有多爱我? 低于10:错误答案等于10以上=好的答案
我知道该怎么做,但是我不希望我每次写答案都停止程序。 我希望程序继续运行直到我有10岁以上。 因此,我始终可以输入,直到10分之10以上。
这是我的台词:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println ("how much do you love me out of 10");
int num1 = input.nextInt();
while (true)
if (num1 <= 9) {
System.out.println("Wrong answer");
}
else {
System.out.println ("Good answer");
}
}
}
这应该工作:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.println ("Out of 10, how much do you love me?");
int input = 0
while (input <= 9) {
input = scanner.nextInt();
if (input <= 9) {
System.out.println("Wrong answer");
} else {
System.out.println("Good answer");
}
}
}
}
说明:它一直循环直到输入不小于或等于9( while (input <= 9)
)。 每次循环时,它都会获取输入并对其进行操作。
希望这可以帮助!
首先,您需要移动int num1 = input.nextInt();
在while循环内的语句,这将在while循环每次循环(迭代)时允许一个新的输入。
其次,如果您希望在num1 >= 10
之前运行程序,则可以通过两种方式实现它。
while(num1 < 10) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
} else {
System.out.println("Wrong answer");
}
}
或使用关键字break
,
while(true) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
break;
} else {
System.out.println("Wrong answer");
}
}
break
只是逃脱了它在调用时所在的循环
希望这有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.