我的代码有效,只有一个问题。该代码用于在两个用户输入之间打印数字。代码的该部分有效,但是,如果第一个数字大于第二个数字,则意味着不打印并再次询问。到那时为止,所有内容都可以使用,但是如果第一个数字大于第二个,控制台和代码就结束了,我不知道为什么吗?你们能帮我解释我做错了吗?谢谢!这是我的代码:
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++);
}
答案 0 :(得分:0)
仅当upperNum> = lowerNum时才开始循环,这意味着循环内的if条件永远不会成立。
要实现输出,您应该执行以下操作。
while (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.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
}
while(lowerNum <= higherNum) {
System.out.println(lowerNum++);
}
答案 1 :(得分:0)
我建议您先使用if条件:
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. ");
} else{
while (higherNum>=lowerNum){
System.out.println(lowerNum++);
}
}
之所以发生这种情况,是因为如果lowerNum
大于higherNum
,则由于错误消息位于while循环内,因此while条件将导致false并且不会输出任何内容。
答案 2 :(得分:0)
您应该早于此。我在修复其他问题。
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int higherNum = 0, lowerNum = 1;
while(lowerNum>=higherNum){
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
if(lowerNum>=higherNum){
System.out.println("Sorry, you put your first number higher than your second, please make your first number a smaller number than your second. ");
} else {
while(lowerNum<higherNum-1){
System.out.println(++lowerNum);
}
}
}
}
答案 3 :(得分:0)
您可以使用重新启动过程的方法来为数字输入。递归选项将有助于解决该问题。
公共无效TakeNumbers(){ 扫描仪阅读器=新的Scanner(System.in);
int higherNum, lowerNum;
System.out.print("First: ");
lowerNum=Integer.parseInt(reader.nextLine());
System.out.print("Second: ");
higherNum=Integer.parseInt(reader.nextLine());
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. ");
TakeNumbers();
System.out.println(lowerNum++);
}
public static void main(String [] args){
TakeNumbers();
}
答案 4 :(得分:0)
只需在下面的链接中,它将在循环中打印以进行确认
https://www.sanfoundry.com/java-program-check-given-number-perfect-number/