Take different values from a String and convert them to Double Values

故事扮演 提交于 2019-12-20 06:32:18

问题


In my code, I'm asking the user to input three different values divided by a blank space. Then, those three different values I would like to assign them to three different Double variables.

I have tried by assigning the first character of such string to my double variables but I haven't been able to succeed.

Any suggestions?

Thank you!

Here is what I'm trying to do:

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));

回答1:


Get the input, split it by a whitespace and parse each Double. This code does not sanitize the input.

        String input = "12.4 19.8776 23.3445";
        String[] split = input.split(" ");
        for(String s : split)
        {
            System.out.println(Double.parseDouble(s));
        }



回答2:


  1. Take input from user.

  2. split that line using delimeter space i.e " ".

  3. inside for loop change each index element to double.By using Double.parseDouble(splitted[i]);




回答3:


You could first split the input using String.split and then parse each variable using Double.parseDouble Double.parseDouble to read them into a Double variable.

String[] params = newDimensions.split(" ");
newHeight = Double.parseDouble(params[0]);
newWidth = Double.parseDouble(params[1]);



回答4:


Double#parseDouble(str) expects a string,and you are trying to pass a character.

try this:

newHeight = Double.parseDouble(newDimensions.subString(1));



回答5:


Try something like this:

newDimensions = JOptionPane.showInputDialog(...

newDimensions = newDimensions.trim();

String arr[] = newDimensions.split(" ");

double darr[] = new double[arr.length];

for(int i=0;i<arr.length;i++) darr[i] = Double.parseDouble(arr[i].trim());

There are still some defensive issues that can be taken. Doing a trim on your parse double is kind of critical.



来源:https://stackoverflow.com/questions/15973624/take-different-values-from-a-string-and-convert-them-to-double-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!