将字符串与输入表单用户进行比较。 java的

时间:2014-09-11 00:38:42

标签: java

这是一段代码

    System.out.println("How would you describe your lifestyle? Sedentary, Somewhat Active, Active, Highly Active?");
    String lifestyle = keyboard.next(); 
 if (lifestyle.equalsIgnoreCase("Somewhat Active"))
 {
  System.out.println("ok");
 }
 else
 {
  System.out.println("not ok")
 }

无论我输入什么,我都无法得到“确定”的回复。

2 个答案:

答案 0 :(得分:2)

Scanner#next()将始终返回下一个令牌,这将只是“Somewhat”。请改用keyboard.nextLine()

答案 1 :(得分:0)

您应该按照hexafraction的建议尝试nextLine()

String lifestyle = keyboard.next(); //<-- input without space, Somewhat
String lifestyle = keyboard.nextLine(); //<-- input with spaces, Somewhat Active