[英]Converting a String ArrayList into a Double ArrayList
I'm trying to convert my String
ArrayList
into a Double
ArrayList
and for some reason it is not converting right. 我正在尝试将我的
String
ArrayList
转换为Double
ArrayList
,由于某种原因,它转换不正确。
My input: 我的输入:
1 2 3 4
My output: 我的输出:
[1.0]
[1.0, 1.0, 2.0]
[1.0, 1.0, 2.0, 1.0, 2.0, 3.0]
[1.0, 1.0, 2.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 4.0]
Expected Output: 预期产量:
[1.0] [1.0, 2.0] [1.0, 2.0, 3.0] [1.0, 2.0, 3.0, 4.0]
My Code 我的密码
String inputValue;
List<String> input = new ArrayList<String>();
List<Double> numbers = new ArrayList<Double>();
while((inputValue = stdin.readLine()) != null) {
input.add(inputValue);
for(int i = 0; i < input.size(); i++) {
numbers.add (Double.parseDouble(input.get(i)));
}
System.out.println(numbers);
}
You don't need two loops - you can convert the String
to double
when you read the input from stdin
. 您不需要两个循环-当您从
stdin
读取输入时,可以将String
转换为double
。 Beside that, the output should be printed after the loop in done, once all the numbers are in the lists : 除此之外,一旦所有数字都在列表中,则输出应在循环完成后打印:
while((inputValue = stdin.readLine()) != null){
input.add(inputValue);
numbers.add (Double.parseDouble(inputValue));
}
System.out.println(numbers);
Actually, I'm not sure you even need the input
list. 实际上,我不确定您是否甚至需要
input
列表。
EDIT : 编辑:
If you want to print the input as it is added to the Lists, and handle bad input, as well as allow the user to quit the loop by typing enter (ie an empty line) : 如果要在将输入添加到列表中时对其进行打印,并处理错误的输入,并允许用户通过键入enter(即空行)退出循环:
while((inputValue = stdin.readLine()) != null && !inputValue.isEmpty()) {
input.add(inputValue);
try {
numbers.add (Double.parseDouble(inputValue));
System.out.println(numbers);
}
catch (NumberFormatException numEx) {
System.out.println(inputValue + " is not a double");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.