2014-01-12 99 views
-7

我無法在這裏定位錯誤:爲什麼我得到「錯誤:'其他'沒有'如果'」?

import java.util.Scanner; 

public class StringExample { 
    public static void main(String[] args) { 
    Scanner myScanner = new Scanner(System.in); 

    System.out.println("What's your favorite type of food?"); 
    System.out.println("1. Pizza?"); 
    System.out.println("2. Steak?"); 
    System.out.println("3. Cake?"); 

    String answer = myScanner.next(); 
    if (answer.equals ("Pizza")) { 
     System.out.println("It's pretty nice, isn't it?"); 
    }else if (answer.equals ("Steak")); { 
     System.out.println("Yummy :)"); 
    }else if (answer.equals ("Cake")); { 
     System.out.println("THE CAKE IS A LIE!"); 
    } 
    } 
    } 

Error: 'else' without 'if'

我得到第17行此錯誤:

}else if (answer.equals ("Cake")); { 
+10

分號具有意義。 –

+0

它看起來像這是偉大的複製粘貼技術的副作用:LOL 你有很多分號人 –

+1

你真的沒有接受答案? –

回答

0

可能兩件事情:

你並不意味着要有分號

您'不小心'刪除了if,最後else

+0

你是什麼意思? – ThievingTime

11

刪除;這些行後:

}else if (answer.equals ("Steak")) 
... 
}else if (answer.equals ("Cake")) 

把一個;會告訴大家,else if身體是空的。

從這個site

The semicolon tells the 'if statement' to do nothing when it is placed directly after it. In other words: if the statement is true do: ';' (nothing)

+0

好的。真棒!修復它。 – ThievingTime

0

檢查這一行,你有一個分號(;)那裏。這兩個語句後

}else if (answer.equals ("Steak")); { 

and 

}else if (answer.equals ("Cake")); { 

使用

}else if (answer.equals ("Steak")) { 

}else if (answer.equals ("Cake")) { 
3

刪除分號

else if (answer.equals ("Steak")); 
else if (answer.equals ("Cake")); 
2
public class StringExample { 
    public static void main(String[] args) { 
    Scanner myScanner = new Scanner(System.in); 

    System.out.println("What's your favorite type of food?"); 
    System.out.println("1. Pizza?"); 
    System.out.println("2. Steak?"); 
    System.out.println("3. Cake?"); 

    String answer = myScanner.next(); 
    if (answer.equals ("Pizza")) { 
     System.out.println("It's pretty nice, isn't it?"); 
    }else if (answer.equals ("Steak")) { 
     System.out.println("Yummy :)") 
    }else if (answer.equals ("Cake")) { 
     System.out.println("THE CAKE IS A LIE!"); 
    } 
    } 
    } 

你不應該後,如果不然,如果條件中使用分號。

1

刪除所有不需要的;

if (answer.equals ("Pizza")) { 
    System.out.println("It's pretty nice, isn't it?"); 
}else if (answer.equals ("Steak")) { 
    System.out.println("Yummy :)") 
}else if (answer.equals ("Cake")) { 
    System.out.println("THE CAKE IS A LIE!") 
} 
0

你已經把一些不必要的;在else if語句之後標記,刪除它。

的if-else if語句看起來像下面

if (condition) 
{ result } 
else if(condition) 
{ result } 
else if(condition) 
{ result } 
else { result } 
0

導致錯誤的:因爲
它 ';'您已包括的符號。將符號想象爲終止符。因此,即使在else if塊被輸入之前,它也會被終止。它讓否則,如果塊空的,這就是爲什麼編譯器正在尋找else語句

正確方法:

if (answer.equals ("Pizza")) { 
    System.out.println("It's pretty nice, isn't it?"); 
}else if (answer.equals ("Steak")) { 
    System.out.println("Yummy :)") 
}else if (answer.equals ("Cake")) { 
    System.out.println("THE CAKE IS A LIE!") 
} 

這將幫助你

相關問題