Java ArrayList\ not working as wanted

huangapple go评论73阅读模式
英文:

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&lt;Double&gt; numberstorage() {
    Scanner s = new Scanner(System.in);
    ArrayList&lt;Double&gt; numbers = new ArrayList&lt;Double&gt;();
    System.out.println(&quot;Enter a number between 0 - 100&quot;);
    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.

huangapple
  • 本文由 发表于 2020年10月7日 10:12:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64236236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定