if语句可以嵌套在while循环中吗?

时间:2013-08-16 04:36:08

标签: java if-statement while-loop do-while

我一直在处理使用do-while循环的代码,我想在该循环中添加if else语句。 do-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: %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语句?

5 个答案:

答案 0 :(得分:2)

在此处检查您的代码是否缺少else阻止:

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

这是编译错误的原因。您可以通过完全删除else或者如果您想在其中添加内容来解决此问题,请执行以下操作:

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

要回答您的问题,是的,在if循环中嵌套while语句是完全有效的。

答案 1 :(得分:0)

您缺少{}来关闭其他区块。而不是

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

使用

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

答案 2 :(得分:0)

因为你的else语句什么也没做,只是让编译器认为while条件是在else条件下而且是错误的。 只需删除它

答案 3 :(得分:0)

很有可能:

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) );

}

答案 4 :(得分:0)

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,偶数!

相关问题