这是我的计算器类,目的是获取键盘输入的字符串运算式并计算出结果
```java
package chap10;
import static java.lang.Integer.parseInt;
public class Calculator {
String str;
public Calculator(String s) {
str = s;
}
String s1 = str.replaceAll(" ", "");
String operator =s1.replaceAll("\\d","");
String[] s2 = s1.split("[\\+\\-\\*\\/]");
public int calculate(){
int result;
int num2 = parseInt(s2[1]);
int num1 = parseInt(s2[0]);
switch(operator.charAt(0)) {
case '+': result=num1+num2;
break;
case'-':result=num1-num2;
break;
case'*':result=num1*num2;
break;
case'/':result=num1/num2;
break;
default:
throw new IllegalStateException("Unexpected value: " + operator.charAt(0));
}
return result;
}
之后,是测试类
```java
package chap10;
import java.util.Scanner;
public class Ex1026 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Please input the expression:");
Calculator calculator=new Calculator(sc.nextLine());
System.out.println(calculator.calculate());
}
}
输入之后,报了空指针异常。请问如何修改。