Search code examples
javaarraysstringparsingdouble

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


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

Solution

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