[英]Java inputMismatchException in calculator
i'm making a calculator but i'm having trouble using the scanner input, i declared the variables as double but if i use i get this error: 我正在做一个计算器,但是在使用扫描仪输入时遇到了麻烦,我将变量声明为double,但是如果我使用,则会出现此错误:
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 ProgramTUI.main(ProgramTUI.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)
Here's the code: 这是代码:
import java.util.Scanner;
public class ProgramTUI {
public static double add(double a, double b) {
return a+b;
}
public static double substract(double a, double b) {
return a-b;
}
public static double multiply(double a, double b) {
return a*b;
}
public static double divide(double a, double b) {
return a/b;
}
public static void main(String[] args) {
int choice;
double a, b;
System.out.println("1- Add");
System.out.println("2- Sub");
System.out.println("3- Mul");
System.out.println("4- Div");
System.out.print("Elige la operacion -");
Scanner var = new Scanner(System.in);
choice = var.nextInt();
System.out.print("Introduce el primer numero -");
a = var.nextDouble();
System.out.print("Introduce el segundo numero -");
b = var.nextDouble();
switch (choice) {
case 1:
System.out.print(add(a,b));
break;
case 2:
System.out.print(substract(a,b));
break;
case 3:
System.out.print(multiply(a,b));
break;
case 4:
System.out.print(divide(a,b));
break;
}
}
}
With int numbers the program work just fine, i declared a and b with var.nextDouble(); 使用int数字,程序运行正常,我用var.nextDouble()声明了a和b; so i don't know what's going on. 所以我不知道发生了什么。
我相信您使用的是错误的小数点分隔符,请尝试如下操作:
Scanner var = new Scanner(System.in).useLocale(Locale.ENGLISH);
You program will fail if whatever you input can not be interpreted as int for var.nextInt();
如果您输入的任何内容都不能解释为var.nextInt();
int,则程序将失败var.nextInt();
and double for var.nextDouble();
并为var.nextDouble();
加倍var.nextDouble();
This might be due to the system locale having another number format. 这可能是由于系统区域设置具有其他数字格式。
You can use this to force the English format: 您可以使用它来强制使用英语格式:
Scanner var = new Scanner(System.in).useLocale(Locale.ENGLISH);
Or you can get the Numbers as strings and parse them 或者,您也可以将数字作为字符串进行解析
try
{
value = Integer.parseInt(value);
}
catch (NumberFormatException e)
{
conversionfailed = true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.