user2221233
user2221233

Reputation: 33

Why is this array not accepting user input?

This is part of a larger assignment. Here, I basically need to accept user input until the user types 0. These doubles need to be added to an array. For some reason, they aren't being added to the array right now. Any help?

public static void main(String[] args){
    Scanner scanner = new Scanner(System.in);
    double[] inputArray = new double[3];
    double input;
    do{
        input = scanner.nextDouble();

    for(int i = 0; i < 3; i++){
        inputArray[i] = input;
    }
    }
    while(input != 0);

    System.out.println("Element 0:" + inputArray[0]);
    System.out.println("Element 1:" + inputArray[1]);
    }

Upvotes: 0

Views: 257

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500055

You're keeping on iterating until input is 0... so on the last iteration of the loop before it terminates, we know that input will be 0.

Now look at what you're doing in the while loop:

for(int i = 0; i < 3; i++){
    inputArray[i] = input;
}

You're replacing all the elements in the array with the current value of input.

So by the time you exit the loop, you've just replaced all the elements with 0.

It would be much better to use a List<Double> with a suitable implementation (e.g. ArrayList<Double>) and just call list.add(input) within the while loop.

Then to print out every element of the list:

for (Double value : list) {
    System.out.println(value);
}

Or if you really want the index:

for (int i = 0; list.size(); i++) {
    System.out.println("Element " + i + ": " + list.get(i));
}

If you have to use an array, you should keep track of how many items you've already set (with a counter incremented in the while loop) and only set one value in the array for each iteration of the loop. Don't forget to terminate the loop if you run out of space in the array, too!

Upvotes: 4

Related Questions