例如,当您键入22和56时,此代码可以正常工作,它显示正确的结果
import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner villy = new Scanner (System.in);
double fnum, snum, answer;
System.out.println("Enter first num: ");
fnum = villy.nextDouble();
System.out.println("Enter second num: ");
snum = villy.nextDouble();
answer = fnum + snum;
System.out.println(answer);
}
}
但是当您尝试将小数放入例如23.53和42.76时,它将失败,并带有以下异常
Exception in thread "main": java.util.InputMismatchException
at java.util.Scanner.throwFor(unknown Source)
at java.util.Scanner.next(unknown Source)
at java.util.Scanner.nextDouble(unknown Source)
at apples.main(apples.java:8)
解决方法:
您是否正在使用非英语计算机?例如,在法国或德国语言环境中,您必须输入23,53,而不是23.53.
扫描程序的默认语言环境是Locale.getDefault()返回的内容:在英语计算机上,它应该返回Locale.ENGLISH.您可以通过以下方法将语言环境设置为英语:
Scanner villy = new Scanner(System.in).useLocale(Locale.ENGLISH);