2012-12-28 65 views
1

我完全是Java的新手,我已經開始使用一些簡單的控制檯應用程序。雖然循環沒有完成

這是我當前的應用程序的代碼:

Scanner sc = new Scanner(System.in); 
boolean ExitLoop = false; 
ArrayList<Integer> IDs = new ArrayList<Integer>(); 
ArrayList<Double> averages = new ArrayList<Double>(); 
while(!ExitLoop) 
{ 
    System.out.println("StudentID: "); 
    IDs.add(sc.nextInt()); 
    System.out.println("Average: "); 
    averages.add(sc.nextDouble()); 
    System.out.println("Do you want to register another student? [y/n] "); 
    ExitLoop = (sc.next() == "n"); 
} 

不好意思問這麼愚蠢的問題,但我真的卡在這,我打的「n」,但while循環沒有停止,繼續工作。我做錯了什麼?當用戶輸入「n」表示「否」時,我應該怎麼做來完成循環?

+3

僅供參考,'do {...} while(!sc.next()。equals(「n」));''是你試圖做的直接構造,而不需要'ExitLoop'標誌。 –

+2

作爲慣例開始您的變量名稱小寫:'exitLoop'和'ids'。否則有人可能會認爲這些是類。 – Simulant

+0

+1 @MarkPeters好的意見,你的解決方案應該是答案。添加它作爲答案,以便我可以接受它。 –

回答

10

的一個問題是:

sc.next() == "n" 

應該

sc.next().equals("n") 

String比較應該用equals()代替==(除了字符串文字比較),它始終是更好地遵循java code conventions

+2

對於OP的好處:http://stackoverflow.com/questions/767372/java-string-equals-versus – NominSim

+0

謝謝你非常。 +1 –

+0

@mahditahsildari:不客氣。祝你好運! – kosa

3

將其更改爲

sc.next().equals("n") 

除此之外檢查Java編碼約定,變量名遵循駝峯

2

試試這個

Scanner sc = new Scanner(System.in); 
      boolean ExitLoop = false; 
      ArrayList<Integer> IDs = new ArrayList<Integer>(); 
      ArrayList<Double> averages = new ArrayList<Double>(); 
      while(!ExitLoop) 
      { 
       System.out.println("StudentID: "); 
       IDs.add(sc.nextInt()); 
       System.out.println("Average: "); 
       averages.add(sc.nextDouble()); 
       System.out.println("Do you want to register another student? [y/n] "); 
       if(sc.next().equals("n")){ 
         ExitLoop = true; 
       } 
      } 

還要注意的是在Java中,如果你想比較字符串的值使用.equals("somevaluhere")如果您想比較其參考用途==

+2

爲什麼你需要一個布爾表達式的三元運算符,其結果被分配給一個布爾變量?這是多餘的。 –

+0

爲什麼不呢? – KyelJmD

+0

那裏我已經更新了我的答案。 – KyelJmD

0

你想退出循環,如果用戶回答「否」,所以你應該只寫

ExitLoop=sc.next().equals("n"); 

,並記住,用戶可以回答「N」。 上面的方法返回一個布爾變量的布爾值,所以你沒問題,你的代碼儘可能簡單。

1

我會謹慎使用.equals(「n」),主要是因爲它比較了整個字符串。如果用戶輸入整個單詞「否」會怎麼樣?這也會導致循環的延續。使用之前使用的==運算符沒有任何問題,您只需確定它所比較的​​內容即可。它適用於char,對於char和String或String和String來說並不是那麼重要。對我來說,一個更好的實現是:

exitLoop = sc.next().charAt(0) == 'n'; 

甚至更​​好:

exitLoop = (sc.next().charAt(0) == 'n' || sc.next().charAt(0) == 'N'); 

而且,現在是開始找出輸入驗證的好時機。

並且不要忘記關閉掃描儀。

0

這將檢查輸入字符串是否以n開頭 ExitLoop = sc.next()。toLowerCase()。startsWith(「n」); // 或者您可能想嘗試忽略大小寫 ExitLoop = sc.next()。toLowerCase()。equals(「n」);