我试图提示用户输入x坐标但是当我写一个十进制数字如2.1作为输入时,这会引起问题。我该如何解决这个问题?
import java.util.Scanner;
public class TwoRetangles{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
System.out.print("Enter the center x coordinate of retangle = ");
double x1=input.nextDouble();
}
}
--------------------配置:--------------------
Enter the center x coordinate of retangle = 2.1
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at TwoRetangles.main(TwoRetangles.java:6)
Process completed.
答案 0 :(得分:4)
你的代码对我有用..我相信扫描仪与你的系统设置有关,所以如果不是美国你不能使用像2.1这样的小数。
如果是这种情况,请执行
Scanner input = new Scanner(System.in).useLocale(Locale.US);
您需要导入java.util。*;
答案 1 :(得分:0)
没有错误。它在我的系统中工作正常。确保你编译正确。它接受了这个值。我试过这个代码并打印2.1:
import java.util.Scanner;
public class TwoRetangles{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
System.out.print("Enter the center x coordinate of retangle = ");
double x1=input.nextDouble();
System.out.print(x1);
}
}