[英]"If" Statement Will Not Print in Loop
我的代码有效,只有一个问题。 该代码旨在打印两个用户输入之间的数字。 代码的那部分有效,但是如果第一个数字大于第二个数字,则意味着不再打印并再次询问。 到目前为止一切正常,但是如果第一个数字大于第二个,控制台和代码就结束了,我不知道为什么? 你们能帮忙解释一下我做错了什么吗? 谢谢! 这是我的代码:
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++);
}
您的循环仅在 highNum >=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++);
}
我建议您先使用 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 条件将导致false 并且不会打印任何内容,因为错误消息在while 循环内。
你的 if 应该在 while 之前。 我在路上修了一些其他的东西。
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);
}
}
}
}
您可以使用重新启动过程的方法提供数字输入。 递归选项将有助于解决该问题。
public void TakeNumbers(){ 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());
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++);
}
公共静态无效主(字符串 [] args){
TakeNumbers();
}
是的,它会在 for 循环内打印以进行确认,只需通过以下链接
https://www.sanfoundry.com/java-program-check-given-number-perfect-number/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.