从String中获取不同的值并将它们转换为Double Values
在我的代码中,我要求用户输入三个不同的值除以空格。 然后,我想将这三个不同的值分配给三个不同的Double变量。
我试过将这样的字符串的第一个字符分配给我的双变量但是我无法成功。
有什么建议?
谢谢!
这是我正在尝试做的事情:
int decision = message(); String newDimensions; double newHeight, newWidth, newLength; if(decision == 1){ newDimensions = JOptionPane.showInputDialog("Please enter the desired amount to be added" + "\nto each dimension." + "\nNOTE: First value is for Height, second for Width, third for Length" + "\nAlso, input information has to have a blank space between each value." + "\nEXAMPLE: 4 8 9"); newHeight = Double.parseDouble(newDimensions.charAt(0));
获取输入,用空格拆分并解析每个Double。 此代码不会清理输入。
String input = "12.4 19.8776 23.3445"; String[] split = input.split(" "); for(String s : split) { System.out.println(Double.parseDouble(s)); }
-
从用户那里获取输入。
-
使用分隔符空间即“”分割该行。
-
inside for循环将每个索引元素更改为double.By使用Double.parseDouble(splitted [i]);
您可以先使用String.split拆分输入,然后使用Double.parseDouble Double.parseDouble解析每个变量,将它们读入Double变量。
String[] params = newDimensions.split(" "); newHeight = Double.parseDouble(params[0]); newWidth = Double.parseDouble(params[1]);
Double#parseDouble(str)需要一个字符串,并且您正在尝试传递一个字符。
试试这个:
newHeight = Double.parseDouble(newDimensions.subString(1));
尝试这样的事情:
newDimensions = JOptionPane.showInputDialog(... newDimensions = newDimensions.trim(); String arr[] = newDimensions.split(" "); double darr[] = new double[arr.length]; for(int i=0;i
仍然存在一些可以采取的防御性问题。 对你的解析双重修改是很重要的。