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

时间:2016-02-15 19:45:00

标签: java string double

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());

            }
        }
    }
}

我想格式化字符串中找到的双打,但我无法将字符串转换为double然后格式化。我是初学者。

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)

2 个答案:

答案 0 :(得分:3)

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())

答案 1 :(得分:0)

如果使用s.nextDouble()方法将此扫描仪输入中的下一个标记解释为double值,则需要使用Double.parseDouble(str)而不是public boolean hasNextDouble()因为nextDouble()返回true 。

你的代码看起来像这样:

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