2

If I execute the following code:

import java.util.Scanner;

public class ScannerTest {

    public static void main(String[] args) {

        Scanner s = null;
        StringBuilder builder = new StringBuilder(64);
        String line = "1.1 2.2 3.3";
        float fsum = 0.0f;      

        s = new Scanner(line).useDelimiter(" ");

        while (s.hasNextFloat()){
            float f = s.nextFloat();
            fsum += f;
            builder.append(f).append(" ");
        }
        System.out.println("Floats found: " + builder);
        System.out.println("Sum: " + fsum);
        s.close();
    }
}

My output is:

Floats found: 
Sum: 0.0

But if I substitute the dots for commas in line "1,1 2,2 3,3", then it does recognize the floats:

Floats found: 1.1 2.2 3.3 
Sum: 6.6000004

I guess it's because my SO is in Spanish, and we use commas instead of dots with decimal numbers. I thought of using Locale, but there isn't Locale.SPANISH.

Furthermore, it behaves just the opposite when I run this:

public class StringToFloatTest {

    public static void main(String[] args) {
        String st = "1,1";
        float f = Float.parseFloat(st);
        System.out.println(f);
    }
}

This code results in a NumberFormatException, but it works if I use String st = "1.1".

Can somebody explain why this happens and how can I make the Scanner recognize the floats with dots?

Luis Sep
  • 2,384
  • 5
  • 27
  • 33
  • 2
    Did you take a look at this post? It seems like it's related to the Locale of your system ( like you guess it ) : http://stackoverflow.com/questions/4708219/weird-behaviour-with-scannernextfloat?rq=1 – Julien Sep 25 '13 at 09:46

2 Answers2

5

Can somebody explain why this happens

As you said, it's using your default locale. Print Locale.getDefault() to check what your default locale is.

Note that Float.parseFloat is not locale-specific.

and how can I make the Scanner recognize the floats with dots?

Call s.useLocale(Locale.US);

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

Java default locale choosing process is described in Java 7 default locale.

And here is how to change it externally without altering the source code in many places: how do I set the default locale for my JVM?

Community
  • 1
  • 1
Vadzim
  • 24,954
  • 11
  • 143
  • 151