Q:

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

            }
        }
    }
}

I want to format the found doubles in the string, but I'm getting unable to convert the string into double and then format.I'm a beginner.
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)

A:

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

Your System.out.format takes in complete str. As a result, you had NumberFormatException. Change it to next token of the string. (s.next())

