问题描述
因此,我想制作一个程序,在该程序中,提示用户输入所需的Double值,然后程序将这些值存储在数组中,直到EOF(当用户按ctl + d时),然后打印这些数字的总和以输出。这就是我到目前为止所拥有的:
So i wanted to produce a program in which the user is prompted to input as many Double values as they want, and the program stores these values in an array until the EOF (when the user presses ctl + d), and then prints the sum of these numbers to output. This is what i have so far:
import java.io.*;
import java.util.*;
public class ArrayExample {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter line: ");
ArrayList<Double> nums = new ArrayList<Double>();
double input = keyboard.nextDouble();
while (input.hasNextLine()) {
input = keyboard.nextDouble();
}
System.out.print(nums);
double sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum+=Integer.parseInt(nums.get(i));
System.out.println(sum);
}
}
}
我的问题是我将如何使用循环保持输入翻倍直到EOF,ArrayList是存储用户输入的最佳方法,并且是获取总和的最正确方法吗?谢谢!
My questions were how would i use a loop to keep reading input doubles until EOF, is the ArrayList the best way to store the users inputs and is that the most correct way to get the sum? Thank you!
推荐答案
修改 while
和 for
按照下面的代码片段循环。在while循环中,只需直接使用Scanner的 hasNextDouble()
方法并将输入的值添加到 Arraylist 。在 for
循环中,您无需将值解析为整数,因为sum是一个double值,这是Arraylist的数据类型。 Arraylist适合您的情况,因为您不确定将从用户那里获得多少值;数组列表可以调整大小。
Modify the while
and for
loops as per the snippet below. In the while loop, just use Scanner's hasNextDouble()
method directly and add values to your Arraylist as they are entered. In the for
loop, you don't need to parse the values to integers since sum is a double which is the datatype of your Arraylist. Arraylist is right for your case since you are not sure of how many values you will get from the user; Arraylists are resizable.
while (keyboard.hasNextDouble()) {
nums.add(keyboard.nextDouble());
}
keyboard.close();
System.out.println(nums);
double sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums.get(i);
}
System.out.println(sum);
这篇关于根据用户输入构造双精度值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!