[java]输入一个算术表达式输出结果
动手有益。
输入一个表达式,没有括号,数字小于0-9之间,输出计算结果,所有的中间结果化为整形。
例如: 输入:3+8×2/9-2
输出:2
/** * input a calculate string, calcuate the value * the number between 0-9 * round the middle vlaue to int * */ public static void main(String[] args) { //8*6+2-6/3*6+2 String cal;//=new Scanner(System.in).nextLine(); cal="8*6+2-6/3*6+2"; String[] car=new String[cal.length()]; for (int i = 0; i < car.length; i++) { car[i]=""+cal.charAt(i); } System.err.println(car); //do * and / for (int i = 0; i < car.length; i++) { if(car[i].equals("*")) { car[i+1]= ""+(Integer.parseInt(car[i-1]) * Integer.parseInt(car[i+1])); car[i-1]=""; car[i]=""; }else if(car[i].equals("/")) { car[i+1]= ""+(Integer)(Integer.parseInt(car[i-1]) / Integer.parseInt(car[i+1])); car[i-1]=""; car[i]=""; } else { continue; } } //do + and - int index=0; for (int i = 0; i < car.length; i++) { index=i; if(car[i].equals("+")) { while(car[++index].equals("")){} car[index]= ""+(Integer.parseInt(car[i-1]) + Integer.parseInt(car[index])); car[i-1]=""; car[i]=""; }else if(car[i].equals("-")) { while(car[++index].equals("")){} car[index]= ""+(Integer.parseInt(car[i-1]) - Integer.parseInt(car[index])); car[i-1]=""; car[i]=""; } else { continue; } } System.err.println(cal+" = "+car[car.length-1]); }