2013-02-22 108 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()也许?)。然后在你的方法中,不要使用“==”作为字符串比较器。