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

后端 未结 5 697
孤街浪徒
孤街浪徒 2021-01-27 09:10

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

相关标签:
5条回答
  • 2021-01-27 09:37

    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.

    0 讨论(0)
  • 2021-01-27 09:39
    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]);

    0 讨论(0)
  • 2021-01-27 09:42

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

    try this:

    newHeight = Double.parseDouble(newDimensions.subString(1));
    
    0 讨论(0)
  • 2021-01-27 09:56

    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]);
    
    0 讨论(0)
  • 2021-01-27 09:57

    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));
            }
    
    0 讨论(0)
提交回复
热议问题