2016-01-24 35 views
0

一切都在編譯,但是當我打印大小和數組元素時,它表示並非所有的值都被添加進來,因爲大小和值只是部分。此外,有時前哨價值不起作用(我必須有時兩次輸入)。有什麼不對?ArrayLists未正確添加值?

import java.util.ArrayList; 
    import java.util.Scanner; 

    public class BowlingScoresArrayList{ 

    public static final int SENTINEL = -999; 
    public static final int MIN=-1; 
    public static void main (String [] Args) { 

    ArrayList<Integer> bowlingScores = new ArrayList<Integer>(); 

    Scanner reader = new Scanner(System.in); 
    System.out.println("Enter your scores: "); 

    do { 
    bowlingScores.add(reader.nextInt()); 
    } while (reader.nextInt()!= SENTINEL); 

    System.out.println(bowlingScores); 
    System.out.println(bowlingScores.size()); 

所以,我想輸入這些值:

Enter your scores: 
    1 
    2 
    2 
    3 
    -999 
    -999 

而且它產生這樣的:

[1, 2, -999] 
    3 
+3

只能叫'reader.nextInt()'*** *** ONCE你的循環中。 –

+1

,這包括循環條件,因爲一旦讀取nextInt(),所獲得的值就用完了。因此,將它讀入**變量**,測試該變量並使用它。發現 –

回答

2

你的問題是,你使用兩個nextInt語句...

do { 
    bowlingScores.add(reader.nextInt()); 
} while (reader.nextInt()!= SENTINEL); 

所以你是askin g用戶提供兩次輸入。

相反,像...

int in = SENTINEL; 
do { 
    in = reader.nextInt(); 
    if (in != SENTINEL) { 
     bowlingScores.add(in); 
    } 
} while (in != SENTINEL); 

會產生預期的效果

+0

重複。 –