簡體   English   中英

if語句可以嵌套在while循環中嗎?

[英]Can if statements be nested in a while loop?

我一直在使用使用do-while循環的代碼,我想在該循環中添加一個if else語句。 do-while循環檢查用戶輸入的文本,如果輸入“exit”一詞,將結束。

public static void main(String[] args) {

    String endProgram = "exit";
    String userInput;
    java.util.Scanner input = new java.util.Scanner(System.in);

    do {

        userInput = input.nextLine();
        if ( !userInput.equalsIgnoreCase(endProgram) ) {
            System.out.printf("You entered the following: %s", userInput);
        } else

    } while ( !userInput.equalsIgnoreCase(endProgram) );

}

當我嘗試編譯此代碼時,我從命令提示符處收到錯誤消息:

SentinelExample.java:20: error: illegal start of expression
            } while ( !userInput.equalsIgnoreCase(endProgram) );
            ^
SentinelExample.java:22: error: while expected
      }
       ^
SentinelExample.java:24: error: reached end of file while parsing
}
 ^

當我在循環中刪除if else語句時,程序編譯正常。 我的程序中的語法有問題嗎? 或者是不可能在while循環中放入if else語句?

這里檢查你的代碼你缺少else塊:

    userInput = input.nextLine();
    if ( !userInput.equalsIgnoreCase(endProgram) ) {
        System.out.printf("You entered the following: %s", userInput);
    } else 

這是編譯錯誤的原因。 您可以通過完全刪除else或者如果要在其中添加else來解決此問題,然后執行以下操作:

    userInput = input.nextLine();
    if ( !userInput.equalsIgnoreCase(endProgram) ) {
        System.out.printf("You entered the following: %s", userInput);
    } else {
        // Do something
    }

並回答你的問題,是的,在while循環中嵌套if語句是完全有效的。

你缺少{}來關閉else塊。 代替

do{
  if(){
  }else
}while()

采用

do{
  if(){
  }else{
  }
}while()

因為你的其他聲明除了讓編譯器認為while條件處於其他條件並且錯誤之外什么都不做。 只需刪除它

很可能:

public static void main(String[] args) {

    String endProgram = "exit";
    String userInput;
    java.util.Scanner input = new java.util.Scanner(System.in);

    do {

        userInput = input.nextLine();
        if ( !userInput.equalsIgnoreCase(endProgram) ) {
            System.out.printf("You entered the following:"+userInput);// use plus ssign instead of %s
        }

    } while ( !userInput.equalsIgnoreCase(endProgram) );

}
package second;

public class Even {

    public static void main(String[] args) {

        int a=0;
        while (a<=100)
        {
            if (a%2==0)
            {
                System.out.println("The no is EVEN : " + a);
            }
            else 
            {
            System.out.println("The num is ODD : " + a);    
            }

        } } }

為什么這不能正常工作,它只顯示0,偶數!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM