在初始阶段,通过输入+或 - 或其他符号,我希望该操作完成并且应该让我输出...而不是为每个数字做整个操作(+, - ,*,/)输入
我尝试了很多次,但仍然收到错误,即使我不知道如何纠正错误。请给我一些建议..
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.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at calculator.Calculator.main(Calculator.java:25
)
package calculator;
import java.util.Scanner;
public class Calculator {
private static int valueA;
private static int valueB;
private static String operator;
private static char operatorA;
public int getValueA() {
return valueA;
}
public int getValueB() {
return valueB;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter problem.");
valueA = keyboard.nextInt();
valueB = keyboard.nextInt();
operator = keyboard.next();
operatorA = operator.charAt(0);
int add = '+' ;
int minus = '-';
int multiply = '*';
int divide = '/';
switch (operatorA) {
case '+':
add=valueA + valueB;
System.out.println(add);
break;
case '-':
minus = valueA - valueB;
System.out.println(minus);
break;
case '*':
multiply=valueA * valueB;
System.out.println(multiply);
break;
case '/':
divide=valueA / valueB;
System.out.println(divide);
break;
default:
System.out.println("unknown operator '" + operator + "'. Please try again.");
break;
}
}
}
答案 0 :(得分:3)
我建议您创建一个double
变量(如果您希望除法运算输出实数),并将每个操作的结果分配给它:
double result = 0.0;
switch ...
...
result = valueA + valueB;
...
result = (double)valueA / valueB; // note cast to double
此外,您发布的错误表示您提供的输入错误。由于您的输入是:
valueA = keyboard.nextInt();
valueB = keyboard.nextInt();
operator = keyboard.next();
您必须按以下顺序输入(例如):
3
4
+
我认为这不是您想要的,因此您可以将输入顺序更改为
valueA = keyboard.nextInt();
operator = keyboard.next();
valueB = keyboard.nextInt();
所以你的输入就像
3
+
4
注意您必须逐个输入数字和运算符。换句话说,输入一个数字(或运算符)并按 Enter ,放入另一个数字并按 Enter 。
答案 1 :(得分:0)
您的错误是输入不匹配。这意味着你输入java不期望的东西 正如你的使用
a.nextInt();
如果你将其他任何东西作为double(0.0 ....)引入它会给你异常。 最简单的解决方案是使用
a.nextDouble();
但当然valueA和valueB必须改为double。它还将修复您的整数转换错误。
此外,您应该将变量更改为
char add = '+' ;
char minus = '-';
char multiply = '*';
char divide = '/';