2014-09-11 64 views
0

以下是一段代碼將字符串與輸入表單用戶進行比較。 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") 
} 

的不管是什麼我型我不能讓一個「OK」的迴應。

回答

3

Scanner#next()將始終返回下一個令牌,這將只是「有點」。改爲使用keyboard.nextLine()

+0

但如何「有點」.equalsIgnoreCase(「有點活躍」)它會返回true? – 2014-09-11 00:40:54

+1

@JunedAhsan不,這兩個字符串不相等。然而,「someWHAT eQuAL」在這樣的比較中是可以接受的。 OP目前使用'next()',它只返回「有點」,這當然不會按照預期進行比較。 – hexafraction 2014-09-11 00:41:41

0

您應該嘗試使用hexafraction建議的nextLine()

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