简体   繁体   中英

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

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 (eg 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM