【发布时间】:2011-06-10 03:25:25
【问题描述】:
在 Eclipse 中运行以下命令最初会导致 Scanner 无法识别控制台中的回车符,从而有效地阻止了进一步的输入:
price = sc.nextFloat();
在代码前添加这一行会使 Scanner 接受 0,23(法语表示法)作为浮点数:
Locale.setDefault(Locale.US);
这很可能是由于 Windows XP Pro(法语/比利时)中的区域设置造成的。当代码再次运行时,仍然接受 0,23,输入 0.23 会导致它抛出 java.util.InputMismatchException。
关于为什么会发生这种情况的任何解释?还有一种解决方法还是我应该只使用Float#parseFloat?
编辑:这演示了 Scanner 在不同区域设置下的行为方式(取消注释开头的一行)。
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);
}
}
【问题讨论】:
-
您能否给出一个可执行示例,显示您正在运行的代码的实际序列并显示问题?
-
当然。我会在几分钟内添加一些代码。