2013-02-22 85 views
0

我試圖要求用戶輸入一個字符(「y」/「n」),並檢查是否是正確的答案。我發現了以下錯誤: 「無法比擬的類型:java.util.Scanner中和java.lang.String中」比較掃描儀到字符串

Scanner userInput = new Scanner(System.in); 

System.out.printf("Is this word spelled correctly?: %s", wordToCheck); 
     rightCheck(userInput); 

public boolean rightCheck(Scanner usersAnswer) 
{ 
    if(usersAnswer == "y") 
    { 
     //"Correct!" 
     //Increment User's Score 
    } 
    else 
    { 
     //"Incorrect" 
     //Decrement User's Score 
    } 
} 

回答

0

我已經修改了你的代碼,沒有測試它,但它應該工作:

Scanner userInput = new Scanner(System.in); 

System.out.println("Is this word spelled correctly?:" + wordToCheck); 
     rightCheck(userInput.next());//send the string rather than the scanner 

public boolean rightCheck(String usersAnswer)//convert the parameter type to String 
{ 
    if(usersAnswer == "y") 
    { 
     //"Correct!" 
     //Increment User's Score 
    } 
    else 
    { 
     //"Incorrect" 
     //Decrement User's Score 
    } 
} 
4

是的,因爲掃描儀是獲得輸入的方式而不是價值本身。你想從輸入中獲取下一個值,然後進行比較。事情是這樣的:

String answer = scanner.next(); 
if (answer.equals("y")) { 
    ... 
} else if (answer.equals("n")) { 
    ... 
} 

請注意,您平時應(包括此情況)比較字符串與==,作爲比較兩個操作數是否指的是完全相同的字符串對象 - 你只關心是否參照等於的對象。 (有關更多詳細信息,請參閱this question)。

+0

你可以通過切換equals'的'參數使程序更不容易出錯: '「Y」 .equals(回答)' 如果'answer'爲'null',則不會拋出'NullPointerException' – cIph3r 2013-02-22 07:15:55

+0

@ cIph3r:'Scanner.next()'永遠不會返回null,所以在這裏不需要這樣做。如果它曾經* did *返回null,那就表明某件事情已經非常糟糕 - 所以我寧願通過一個異常來了解它,而不是在一個破碎的世界中繼續。 – 2013-02-22 07:18:29

+0

好吧,對。我是'scanner.next()'的情況,沒有空​​值。但總的來說,這可以防止這種錯誤。 – cIph3r 2013-02-22 07:24:46

0

我相信你應該先從掃描儀獲取字符串(通過next()也許?)。然後在你的方法中,不要使用「==」作爲字符串比較器。