简体   繁体   English

为什么此数组不接受用户输入?

[英]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. 在这里,我基本上需要接受用户输入,直到用户键入0。这些双精度数需要添加到数组中。 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. 您一直在迭代直到input为0 ...所以在循环终止之前的最后一次迭代中,我们知道input 将为 0。

Now look at what you're doing in the while loop: 现在来看一下while循环中的操作:

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 . 您正在用input的当前值替换数组中的所有元素。

So by the time you exit the loop, you've just replaced all the elements with 0. 因此,在退出循环时,您已经将所有元素替换为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. 最好使用具有适当实现的List<Double> (例如ArrayList<Double> )并在while循环内仅调用list.add(input)

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. 如果必须使用数组,则应跟踪已设置的项数(在while循环中增加一个计数器),并且每次循环的迭代仅在数组中设置一个值。 Don't forget to terminate the loop if you run out of space in the array, too! 如果阵列中的空间不足,也不要忘记终止循环!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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