[英]"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.