2014-10-19 213 views
0

我在APCS類中有一項任務,要求我們創建組合鎖,並且我認爲我已經完成了基本結構。但是,我一直遇到一個問題,它不會讓我比較原始的nextLine()String如何將nextLine()與字符串進行比較

我想知道nextLine()是默認的int s?或者任何人都可以告訴我我的代碼有什麼問題?

if((in.nextLine()).compareTo(combo)) 
    { 
     System.out.println("The lock is now unlocked."); 
     System.out.println("Please enter the combo to unlock: "); 
     if((in.nextLine()).compareTo(combo)) 
     { 
      System.out.println("The lock is now locked."); 

     } 
     else 
     { 
      System.exit(0); 
     } 
    } 

P. IDE將返回錯誤:「錯誤:不兼容的類型:int不能轉換爲布爾值」並且指的是如果資格。

回答

3

nextLine()將始終返回一個字符串,所以這不是你的問題。

compareTo(str)返回一個負數如果str字典順序是小於該值被比較於0,如果字符串是字典順序相等,或者如果str的正數是字典順序大於值多的被比較。

你想使用equals(str),它返回一個布爾值。

+0

謝謝,那是問題所在,它現在可行。 – 2014-10-19 04:42:47

2

你的問題是,compareTo()返回一個整數值,而不是布爾值。

見的compareTo了Java API文檔(接口相媲美,在http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html):

Method Detail

compareTo

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

比較兩個字符串的最簡單的方法是使用

if (in.nextLine().equals(combo)) { /* code here */ } 

當心另一個陷阱中這個節目也是。你的第一個nextLine()和你的第二個nextLine()實際上是兩個單獨的輸入行。 nextLine()返回來自閱讀器的下一行輸入,因此每次調用它時都會返回不同的輸入行。一種解決方案是將nextLine()的結果保存爲變量:

String enteredCombo = in.nextLine(); 
if (enteredCombo.equals(combo)) 
{ 
    System.out.println("The lock is now unlocked."); 
    System.out.println("Please enter the combo to lock: "); 
    enteredCombo = in.nextLine(); 
    if(enteredCombo.equals(combo)) 
    { 
     System.out.println("The lock is now locked."); 
    } 
    else 
    { 
     System.exit(0); 
    } 
} 
相關問題