Home > Blockchain >  How can I convert a string into a double after a specific key word?
How can I convert a string into a double after a specific key word?

Time:11-08

I want to create a method that converts a string-value into a double after a specific string.
For example:
String text1 = "--generalus! -maximus? --petrus 23 --param 123.456";
I am searching for the value after the word param has appeared. If there is no param-word, I have to return a Double.NaN. I tried to split the String into an array to work with the index but the parseDouble-method isn't working... Can you maybe help me?

    public double parseParam(String text) {
        String[] arr = text.split("\\s");
        String param = "param";
        for (int i = 0; i < arr.length;i  ){
            System.out.println(arr[i]); //just for me to show whats going on
            if(arr[i].equals(param)){
                return Double.parseDouble(arr[i 1]); 
            }
        }
        return Double.NaN;
    }

CodePudding user response:

You could use a regular expression. Find --param followed by one or more whitespace and then a floating point value. Group that value. And then parse it (if it is found). Like,

String text1 = "--generalus! -maximus? --petrus  23 --param 123.456";
Pattern p = Pattern.compile("--param\\s ([ -]?\\d*([.]?\\d ))");
Matcher m = p.matcher(text1);
double val = Double.NaN;
if (m.find()) {
    val = Double.parseDouble(m.group(1));
}
System.out.println(val);

Outputs

123.456

CodePudding user response:

It may be needed to parse all the parameters in the input string which resemble command-line options using a 3rd-party library such as Apache Commons CLI, or a map of key-value pairs may be built and relevant parameter could be be retrieved from the map by the parameter name:

String text1 = "--generalus! -maximus? --petrus  23 --param 123.456";
Map<String, String> map = Arrays.stream(text1.split("[\\-] ")) // Stream<String>
      .filter(s -> s != null && !s.trim().isEmpty()) // remove blanks
      .map(pair -> pair.split("\\s ")) // Stream<String[]> pairs
      .collect(Collectors.toMap(
          p -> p[0],
          p -> p.length > 1 ? p[1] : ""
      ));
System.out.println(map);
// available parameter
System.out.println(Double.parseDouble(map.getOrDefault("param", "NaN")));
// missing parameter
System.out.println(Double.parseDouble(map.getOrDefault("param1", "NaN")));

Output:

{maximus?=, petrus=23, param=123.456, generalus!=}
123.456
NaN

CodePudding user response:

It will work if you compare "--param" instead of "param".

  • Related