Take the 2-minute tour ×

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;
        input = scanner.nextDouble();

        inputArray[i] = input;
    while(input != 0);

    System.out.println("Element 0:" + inputArray[0]);
    System.out.println("Element 1:" + inputArray[1]);
share|improve this question
add comment

1 Answer

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:

    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) {

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!

share|improve this answer
add comment

Your Answer


