Weird behaviour with Scanner#nextFloat
Posted
by
James P.
on Stack Overflow
See other posts from Stack Overflow
or by James P.
Published on 2011-01-16T21:33:00Z
Indexed on
2011/01/16
21:53 UTC
Read the original article
Hit count: 171
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);
}
}
© Stack Overflow or respective owner