运行在Eclipse下最初引起扫描器不能有效地阻止进一步的输入控制台承认回车:
price = sc.nextFloat();
加入这一行的代码会导致扫描仪接受0,23(法语符号)作为浮动之前:
Locale.setDefault(Locale.US);
这是最有可能是由于在Windows XP专业版的区域设置(法国/比利时)。 当运行代码再次0,23仍在接受并输入0.23使其抛出java.util.InputMismatchException
。
没有解释为什么发生这种情况? 也有一种解决方法,或者我应该只使用Float#parseFloat
?
编辑:这显示扫描仪具有不同的语言环境(开头的行取消注释之一)的行为。
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();
}
System.out.println("Switching Scanner to System.in");
try{
sc = new Scanner(System.in);
System.out.println("Enter a float value");
price = sc.nextFloat();
System.out.println(price);
} catch (java.util.InputMismatchException e){
e.printStackTrace();
}
System.out.print("Enter title:");
String title = sc.nextLine(); // This line is skipped
System.out.print(title);
}
}
编辑:这再现扫描器在等待一个浮动值,但失败,当你按回车键来触发这个问题:
import java.util.Scanner;
public class IgnoreCRTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a float value:");
// On french Locale use , as the decimal separator
float testFloat = sc.nextFloat();
System.out.println(testFloat);
//sc.skip("\n"); // This doesn't solve the issue
sc.nextLine();
System.out.println("Enter an integer value:");
int testInt = sc.nextInt();
System.out.println(testInt);
// Will either block or skip here
System.out.println("Enter a string value :");
String testString = sc.nextLine();
System.out.println(testString);
}
}