其返回值为一个数组:其中第一元素表示求值结果,第二个元素表示它已解析的字符数。
import java.util.Scanner; public class 逆波兰表达式 { public static void main(String[] args) { Scanner s=new Scanner(System.in); String x=s.nextLine(); int a[]=evaluate(x); System.out.println(a[0]+" "+a[1]); } static int[] evaluate(String x) { if(x.length()==0) return new int[] {0,0}; char c = x.charAt(0); if(c>='0' && c<='9') return new int[] {c-'0',1}; int[] v1 = evaluate(x.substring(1)); int[] v2 = evaluate(x.substring(1+v1[1])); //填空位置,v2从v1的下一个开始继续遍历,此函数方法是从此 位置开始到字符串末尾,生成子字符串 int v = Integer.MAX_VALUE; if(c=='+') v = v1[0] + v2[0]; if(c=='*') v = v1[0] * v2[0]; if(c=='-') v = v1[0] - v2[0]; return new int[] {v,1+v1[1]+v2[1]}; } }