英文:
Java ArrayList<double> not working as wanted
问题
以下是您要翻译的内容:
我正在尝试编写一个程序,该程序将通过用户输入数字,并将数字存储到一个ArrayList中。目前我有:
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("输入一个在0 - 100之间的数字");
do {
numbers.add(s.nextDouble());
} while (s.nextDouble() != 0);
s.close();
return numbers;
}
当我输入1、2、3时,出现了输出为1.0、3.0的问题。有没有什么原因导致它跳过了一行输入?
英文:
I'm trying to write a program that will take numbers input through a user and store the numbers into an 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. Is there a reason it's skipping one line of input?
答案1
得分: 1
你在每次循环中都调用了 s.nextDouble()
-- 一次是将其添加到 numbers
中,另一次是检查 while
条件。
相反地,你只需要调用一次,并且在每次使用时都使用相同的值。将其存储在一个变量中。
英文:
You call s.nextDouble()
twice per loop -- once to add it to numbers
, and once to check the while
condition.
Instead, you only want to call it once, and use the same value each time. Store it in a variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论