2013-08-16 150 views
0

我一直在处理使用do-while循环的代码,并且我想在该循环中添加if else语句。 do-while循环检查用户输入的文本,如果输入单词“exit”,将会结束。if语句是否可以嵌套在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语句?

+0

我不明白为什么不。 –

+2

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

+0

你有一个没用的else关键字 –

回答

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 
    } 

并回答你的问题,是的,它是完全有效的窝在一个while循环if语句。

0

您缺少{}来关闭else块。取而代之的

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

使用

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

,由于你的其他statment,什么也不做,但让编译器认为,虽然条件是其他条件和错误下。 只是将其删除

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

} 
+0

你不需要其他.. – Abhishek

+0

@SusanYanders:预期的输出是什么? – Abhishek

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,甚至!

+0

因为你使用while语句错误。你想做的事情应该用for循环来完成,比如“for(int a = 0; a <= 100; a ++)”。 – vshcherbinin