0

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]);
    }

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.