2016-01-24 65 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

重复。 –