繁体   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