0

Everything compiles, but when I print the size and the array elements, it indicates that not all of the values are added in because the size and the values would only be partial. Also, sometimes the sentinel value does not work( I have to enter it twice at times).What's wrong?

    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());

So I tried entering these values:

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

And it yields this:

    [1, 2, -999]
    3
Charlotte
  • 1
  • 1

1 Answers1

2

You're problem is, you're using two nextInt statements...

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

So you're asking the user to provide input twice.

Instead, something like...

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

would produce the desired results

MadProgrammer
  • 323,026
  • 21
  • 204
  • 329