[英]Java ArrayList<double> not working as wanted
I'm trying to write a program that will take numbers input through a user and store the numbers into an ArrayList.我正在尝试编写一个程序,该程序将通过用户输入数字并将数字存储到 ArrayList 中。 Currently I have:
目前我有:
public static void main(String[] args) {
System.out.println(numberstorage());
}
public static ArrayList<Double> numberstorage() {
Scanner s = new Scanner(System.in);
ArrayList<Double> numbers = new ArrayList<Double>();
System.out.println("Enter a number between 0 - 100");
do {
numbers.add(s.nextDouble());
} while (s.nextDouble() != 0);
s.close();
return numbers;
}
When I input 1, 2, 3, for some reason my output is 1.0, 3.0.当我输入 1、2、3 时,由于某种原因,我的输出是 1.0、3.0。 Is there a reason it's skipping one line of input?
是否有理由跳过一行输入?
You call s.nextDouble()
twice per loop -- once to add it to numbers
, and once to check the while
condition.每个循环调用
s.nextDouble()
两次——一次将它添加到numbers
,一次检查while
条件。
Instead, you only want to call it once, and use the same value each time.相反,您只想调用它一次,并且每次都使用相同的值。 Store it in a variable.
将其存储在变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.