Take different values from a String and convert th

2019-03-04 05:13发布

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

5条回答
Rolldiameter
2楼-- · 2019-03-04 05:28

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.

查看更多
老娘就宠你
3楼-- · 2019-03-04 05:30

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楼-- · 2019-03-04 05:33

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));
        }
查看更多
萌系小妹纸
5楼-- · 2019-03-04 05:43
  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]);

查看更多
冷血范
6楼-- · 2019-03-04 05:44

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

try this:

newHeight = Double.parseDouble(newDimensions.subString(1));
查看更多
登录 后发表回答