2013-09-23 58 views
0

所以我對Java相當陌生,我試圖運行一個程序,它將顯示一個名稱中的一定數量的字母並詢問用戶的響應。用戶的回答應該確定兩個答案之一(「正確」或「我很抱歉,這是不正確的」)。 我遇到的問題是,當我運行該程序並輸入應導致「正確」的答案,即「比利喬爾」時,我收到了「我很抱歉,這是不正確的」的回覆。 我真的不知道發生了什麼,但是當我輸入什麼應該導致系統說「正確」,而是說「對不起,這是不正確的」時,這裏是CMD圖片的鏈接:系統輸出困難

enter image description here

這裏是相關的代碼的副本:

System.out.println("\nLet's play Guess the Celebrity Name."); 

String s6 = "Billy Joel"; 

System.out.println("\n" + s6.substring(2, 7)); 

Scanner kbReader3 = new Scanner(System.in); 
System.out 
     .print("\nPlease enter a guess for the name of the above celebrity: "); 
String response = kbReader3.nextLine(); 

System.out.println("\nYou entered: \n" + response + "\n"); 

if ((response == "Billy Joel")) { 
    // Execute the code here if Billy Joel is entered 
    System.out.println("\nCorrect!"); 
} else { 
    // Execute the code here if Billy Joel is not entered 
    System.out.println("\nI'm sorry, that's incorrect. The right answer was Billy Joel."); 
} 

System.out.println("\nThank you for playing!"); 

還有更多在此之前,該方案也做,但我沒有與任何一個問題,這是正確的。我拿出比利喬爾的一部分,其他所有東西都按照它應有的原樣運行。這只是上面的代碼,關於它應該發佈什麼以及它發佈的是什麼問題。我想知道如果我在我的代碼中丟失了某些東西,或者我錯了,但是無論我做了什麼,都會非常感激。

+8

不要將字符串值與== ==運算符進行比較,可以使用String的equals方法比較字符串值。 – rgettman

+0

您的鏈接已損壞。無論如何,你可以並且應該在這裏發佈圖片。 – 2013-09-23 22:41:28

回答

0

你的問題在於這裏。您正在使用錯誤的操作比較字符串

if ((response **==** "Billy Joel")) { 
    System.out.println("\nCorrect!"); 
} else { ... } 

正確的應該是

if ((response.equals("Billy Joel")) { 
    System.out.println("\nCorrect!"); 
} else { ... } 

要你必須使用.equals()操作的java比較字符串。要使用'=='運算符,您需要int,bool等。

+2

「比利喬爾」.equals(響應)將減少獲得空指針異常的風險。 – porfiriopartida

+0

@porfiriopartida的確如此 –

0
if (response!=null && response.length>0){ 
    //trim the input to make sure there are any spaces 
    String trimmed=response.trim(); 
    if (response.equals(s6)) 
     System.out.println("\nCorrect!"); 
    } else { ... }