编程新手。
我在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");
}
}
}
答案 0 :(得分:0)
This should work:
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");
}
}
}
}
Explanation: It loops until input is less not less than or equal to 9 (while (input <= 9)
). Each time through the loop, it gets input and acts on it.
Hope this helps!
答案 1 :(得分:0)
First off, you need to move the int num1 = input.nextInt();
statement inside your while loop, this will allow for a new input every time the while loop loops (iterates).
Second, if you are looking to run the program until num1 >= 10
, then you could implement it in two ways.
while(num1 < 10) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
} else {
System.out.println("Wrong answer");
}
}
or using the keyword break
,
while(true) {
num1 = input.nextInt();
if(num1 >= 10) {
System.out.println("Good answer");
break;
} else {
System.out.println("Wrong answer");
}
}
break
simply escapes the loop it resides in when called
Hoped this helped