【发布时间】:2020-01-08 07:16:44
【问题描述】:
我的代码有效,只有一个问题。该代码旨在打印两个用户输入之间的数字。这部分代码有效,但是如果第一个数字大于第二个数字,则意味着不会打印并再次询问。到目前为止一切正常,但是如果第一个数字大于第二个数字,控制台和代码就会结束,我不知道为什么?你们能帮忙解释一下我做错了什么吗?谢谢!这是我的代码:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int higherNum, lowerNum;
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
while (higherNum>=lowerNum){
if (lowerNum>higherNum){
System.out.print("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. "); // this does not print
}
}
System.out.println(lowerNum++);
}
【问题讨论】:
-
提示:如果
lowerNum大于higherNum,则while循环的条件将从一开始就计算为false。 -
当你的循环检查相反时,应该如何检查 if ?如果你想至少执行一次 if 来检查输入,你想使用 do-while 循环
-
while 和 if 语句的条件是互补的:如果 while 条件为真,if 条件为假。
标签: java loops if-statement printing while-loop