Weird behaviour with Scanner#nextFloat
- by James P.
Running the following in Eclipse initially caused Scanner to not recognize carriage returns in the console effectively blocking further input:
price = sc.nextFloat();
Adding this line before the code causes Scanner to accept 0,23 (french notation) as a float:
Locale.setDefault(Locale.US);
This is most probably due to regional settings in Windows XP Pro. When the code is run again 0,23 is still accepted and entering 0.23 causes it to throw a java.util.InputMismatchException.
Any explanation as to why this is happening? Also is there a workaround or should I just use Float#parseFloat?
Edit:
import java.util.Locale;
import java.util.Scanner;
public class NexFloatTest {
public static void main(String[] args) {
//Locale.setDefault(Locale.US);
//Locale.setDefault(Locale.FRANCE);
// Gives fr_BE on this system
System.out.println(Locale.getDefault());
float price;
String uSDecimal = "0.23";
String frenchDecimal = "0,23";
Scanner sc = new Scanner(uSDecimal);
try{
price = sc.nextFloat();
System.out.println(price);
} catch (java.util.InputMismatchException e){
e.printStackTrace();
}
try{
sc = new Scanner(frenchDecimal);
price = sc.nextFloat();
System.out.println(price);
} catch (java.util.InputMismatchException e){
e.printStackTrace();
}
String title = null;
System.out.print("Enter title:");
try{
title = sc.nextLine(); // This line is skippe
} catch(java.util.NoSuchElementException e ){
e.printStackTrace();
}
System.out.print(title);
}
}