2016-08-14 49 views
-3

我正在準備亞奧理事會8檢查...嵌套如果 - 別人在Java中

有在enthuware測試一個問題,什麼是下面的代碼的正常結構(如果屬於哪個別的喜歡哪個 - 沒有大括號)?

... 

if 
    statement 1; 
if 
    statement 2; 
else 
    statement 3; 
else 
    statement 4; 

... 

在enthuware提供的答案是這樣的...

if //statement 1 
| if //statement 2 
| | 
| else //statement 3 
else //statement 4 

,但是當我在Eclipse執行代碼(沒有大括號),我在最後還有一個編譯時錯誤...

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Syntax error on token "else", delete this token 

那麼,這是正確的/有效的/可能的嗎?

+2

你能提供[mcve]嗎? – 2016-08-14 16:20:03

+1

這不是有效的代碼。你有1,如果加上另一個,如果有兩個elses – Bohemian

+0

@Bohemian我認爲第二個'if'和它的'else'嵌套在第一個'if'中。這很難遵守,所以我可能是錯的。無論哪種方式,在測試中提出這樣的問題都毫無意義。這可能是有效的,但對於皮特的愛只是使用大括號。 –

回答

0

如果你不把大括號,只有if()後的第一個語句被認爲。在你的情況下,兩個if語句是嵌套的,但第一個else聲明是父母if,因此第二個else沒有if

-1

每天如果沒有括號的條件後,只需一個語句,所以:

if(value) 
Sys.out.print("Cow"); 
Sys.out.print("Rabbit"); 

這裏,"Cow"會如果value是真實的打印。但是,每次都會打印"Rabbit"。爲了確保二/多指令執行所依據的if語句,你必須使用塊像:

if(value){ 
Sys.out.print("Cow"); 
Sys.out.print("Rabbit"); 
} 

所以當沒有括號它不會爲編譯:

if 
    statement 2; 
else 
    statement 3; 

這被視爲一個,只有一個被認爲是如果陳述。第一個「if」只是一個獨立的if語句,因此第二個else語句是錯誤的,因爲它沒有在它之前的語句。

-1

沒有大括號:

if (true) 
     System.out.println("First if"); 
    else 
     if (true) 
      System.out.println("second if, first else"); 
     else 
      System.out.println("second if, second else"); 

    System.out.println("outside statement"); 

雖然我會強烈建議將它們添加:

if (true) { 
     System.out.println("First if"); 
    } else if (true) { 
     System.out.println("second if, first else"); 
    } else { 
     System.out.println("second if, second else"); 
    } 

    System.out.println("outside statement");