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?
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);
See more on this question at Stackoverflow