2013-08-16 3 views
0

do-while 루프를 사용하는 코드로 작업하고 있었고 if 루프에 if else 문을 추가하려고했습니다. do-while 루프는 사용자가 입력 한 텍스트를 확인하고 'exit'라는 단어가 입력되면 완료됩니다. 이 코드를 컴파일 할 때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: %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 
} 
^ 

내가 루프의 경우 다른 문을 제거하면, 프로그램은 잘 컴파일합니다. 내 프로그램의 문법에 문제가 있습니까? 또는 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 (int a = 0; a <= 100; a ++)"와 같은 for-loop로해야합니다. – vshcherbinin