2015-10-17 758 views
-3

我不確定爲什麼我的if else語句在這個程序中不起作用。If-else語句錯誤'else'without'if'

int roll = (int) (Math.random()*7 + 1); 

System.out.println("Rolled: " + roll); 
System.out.println("Enter 'r' to roll again or 'h' to hold"); 
String answer = scan.next(); 
String answer1 = answer.toUpperCase(); 

if (answer1=="R"){ 
    int roll2 = (int) (Math.random()*7 + 1); 
    System.out.println("Rolled: " + roll2); 
else { 
    System.out.println("Your score = " + roll); 
}  
+1

Watttch youse bracketsess ... –

+0

@MartinJames我從來沒有見過咕嚕之前回答編程問題...哈哈 – zerobandwidth

回答

0

當你碰到else時,你就在'if {'塊中,因此是錯誤信息。配上你的括號,爲樂趣和利潤。

如果您已經縮進代碼,開始時,你可能已經沒有SO問題:(

0

在這裏你去注意到它。見支架添加在其他行的開頭。

int roll = (int) (Math.random()*7 + 1); 

System.out.println("Rolled: " + roll); 
System.out.println("Enter 'r' to roll again or 'h' to hold"); 
String answer = scan.next(); 
String answer1 = answer.toUpperCase(); 

if (answer1=="R"){ 
    int roll2 = (int) (Math.random()*7 + 1); 
    System.out.println("Rolled: " + roll2); 
} else { 
    System.out.println("Your score = " + roll); 
} 
1

我認爲你的問題會由一些更仔細的編碼風格,可以輕鬆解決。

if(answer1 == "R") 
{ 
    int roll2 = (int)(Math.random() * 7 + 1) ; 
    System.out.println("Rolled: " + roll2) ; 
} // This one's missing in your code, and is the problem. 
else 
{ 
    System.out.println("Your score = " + roll) ; 
} 

順便說一句,你if()條件永遠不會爲真,但我會升如果你發現自己.equals()來完成這項任務,那麼這就是爲什麼作爲練習讀者的原因。

+0

'更仔細的編碼風格' - 完全:) –

0

嘗試縮進並隔開您的代碼,答案很快就會顯現。

int roll = (int) (Math.random()*7 + 1); 

System.out.println("Rolled: " + roll); 
System.out.println("Enter 'r' to roll again or 'h' to hold"); 
String answer = scan.next(); 
String answer1 = answer.toUpperCase(); 

if (answer1=="R") 
{ 
    int roll2 = (int) (Math.random()*7 + 1); 
    System.out.println("Rolled: " + roll2); 
//MISSING BRACKET 
else 
{ 
    System.out.println("Your score = " + roll); 
}  
0

像許多其他人一樣,你忘記了if的結尾括號。如果你的代碼縮進了,你會很容易發現錯誤。一些編輯器,如Eclipse和GNU Emacs,具有自動縮進功能。 此外,您必須使用equals方法來比較字符串。 How do I compare strings in Java?