Home > Software design >  I want to parse a string and get a double value (java)
I want to parse a string and get a double value (java)

Time:06-17

I want to parse a string and get a double value. For example, I input "65.2 hello". I want to get "65.2" Will I?

 while(scanner.hasNextLine()) {
  String ReadString =  scanner.nextLine();
  double value = Double.parseDouble(ReadString);

Exception in thread "main" java.lang.NumberFormatException: For input string: "65.2 hello"
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:549)
at com.company.Main.main(Main.java:18)

CodePudding user response:

Because at least part of the String can't be converted to a double, you need to remove that part of the String before you can use parseDouble on it.

CodePudding user response:

Try this.

Scanner scanner = new Scanner("65.2 hello");
while(scanner.hasNextDouble()) {
      double value =  scanner.nextDouble();
      System.out.println(value);
}

output:

65.2
  • Related