// 用户从命令行窗口输入算式,如2+3或3*2等,输出运行结果。
一眼以为是最基础的数字运算,分别读入并计算。实则是输入一个由两个数字,一个运算符(+、-、*、/)组合成的一个字符串,我们需要做的是读入这个字符串,拆分字符串,判断数字和运算方法。用的递归实现。有两处容易踩坑1.有多行输入hasNext()要括住整个方法体;2.按照输出样例,需将double结果(也只有“/”时需要考虑)强制转换为int型。
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
while (scan.hasNext()) {
String s=scan.nextLine();
System.out.println((int)getResult(s));
}
}
private static boolean isNumber(String str) {//判断表达式是不是只有一个数字
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i)) && str.charAt(i) != '.' && str.charAt(i) != ' ') {
return false;
}
}
return true;
}
public static double getResult(String str) {//解析算式,并计算算式结果;
// 递归头
if (str.isEmpty() || isNumber(str)) {
return str.isEmpty() ? 0 : Double.parseDouble(str);
}
//递归体
if (str.contains("+")) {
int index = str.lastIndexOf("+");
return getResult(str.substring(0, index)) + getResult(str.substring(index + 1));
}
if (str.contains("-")) {
int index = str.lastIndexOf("-");
return getResult(str.substring(0, index)) - getResult(str.substring(index + 1));
}
if (str.contains("*")) {
int index = str.lastIndexOf("*");
return getResult(str.substring(0, index)) * getResult(str.substring(index + 1));
}
if (str.contains("/")) {
int index = str.lastIndexOf("/");
return getResult(str.substring(0, index)) / getResult(str.substring(index + 1));
}
// 出错
return 0;
}
}
测试可以通过)