试图在字符串中找到双打并转换为正确的格式

Trying to find doubles in string and convert into correct format

import java.util.Scanner;
public class LearnHasNext
{
    public static void main(String [] args) {
        String str = "Hello String with doubles 340046.0 2896.013478 3.0 ";
        Scanner s  = new Scanner(str);
        // hasNext scans through the whole string 
        while(s.hasNext()) {
            // looks up there's a double in the string 
            if(s.hasNextDouble()) {
                // if there's no double then just prints next statement entity 
                System.out.format("The scanned double is : " + "%,3f \n",Double.parseDouble(str));
            } 
            else {
                 System.out.println("We are left with "+s.next());

            }
        }
    }
}

我想格式化字符串中找到的双精度数,但我无法将字符串转换为双精度数,然后format.I我是初学者。

Output:
We are left with Hello
We are left with String
We are left with with
We are left with doubles
Exception in thread "main" java.lang.NumberFormatException: For       input  string: "Hello String with doubles 340046.0 2896.013478 3.0"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at LearnHasNext.main(LearnHasNext.java:12)
public static void main(String[] args) {
    String str = "Hello String with doubles 340046.0 2896.013478 3.0 ";
    Scanner s = new Scanner(str);
    while (s.hasNext()) {
        if (s.hasNextDouble()) {                
            System.out.format("The scanned double is : " + "%.3f \n", Double.parseDouble(s.next()));
        } else {
            System.out.println("We are left with " + s.next());
        }
    }
}

您的 System.out.format 接受了完整的 str。结果,您遇到了 NumberFormatException。将其更改为字符串的下一个标记。 (s.next())

您需要使用 s.nextDouble() 而不是 Double.parseDouble(str) 因为 public boolean hasNextDouble()returns 如果此扫描器输入中的下一个标记可以使用nextDouble() 方法。

您的代码看起来像这样:

    public static void main(String [] args) {
       String str = "Hello String with doubles 340046.0 2896.013478 3.0 ";

       Scanner s  = new Scanner(str);
       // hasNext scans through the whole string 
       while(s.hasNext()) {
           // looks up there's a double in the string 

          if(s.hasNextDouble()) {
              // if there's no double then just prints next statement entity 
              System.out.format("The scanned double is : " + "%,3f \n",s.nextDouble());
          } else { System.out.println("We are left with "+s.next()); }
       }
    }