import java.util.Scanner;
public class EvaluationExpression {
//Operation
public static int opration(int num1, int num2,char ope) {
int result = 0;
switch(ope) {
case '+':
result = num1 + num2;;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Please enter the correct expression");
}
return result;
}
//Main method
public static void main(String[] args) {
// Prompt the user to enter a evaluation expression
System.out.print("Enthe a evaluation expression: ");
Scanner input = new Scanner(System.in);
String expression = input.nextLine();
//Create two arrays to store operands and operators
int numberLength = expression.length() / 2 + 1;
int operatorLength = numberLength;
int[] number= new int[numberLength];
char[] operator = new char[operatorLength];
//Add members
int j = 0,k = 1;
for(int i = 0;i < expression.length();i++) {
operator[0] = '+';
char n = expression.charAt(i);
if(Character.isDigit(n)) {
int member = n - 48;
number[j] = member;
j++;
}
else {
operator[k] = n;
k++;
}
}
//Look for the multiplication or division sign
int judge = 0,specialcount = 0;
int[] indexOfOperator = new int[operatorLength];
int[] advancedOperate = new int[numberLength];
for(int i = 0,a = 0;i < operator.length;i++) {//确定表达式中“*”或“/”的位置
if(operator[i] == '*' || operator[i] == '/') {
indexOfOperator[a] = i;
a++;
judge = i;
specialcount++;
}
}
//Operate
int result = 0;
if(judge == 0) {//表达式是只有加减运算
for(int a = 0,b = 0;a < numberLength && b < operatorLength;a++,b++) {
result = opration(result,number[a],operator[b]);
}
}
else if(specialcount == operatorLength-1){//表达式只有乘除运算
for(int a = 0,b = 0;a < numberLength && b < operatorLength;a++,b++) {
result = opration(result,number[a],operator[b]);
}
}
else {//表达式为混合运算
for(int i = 1,a = 0;i < indexOfOperator.length;i++) {
//如果存储运算符号的数组里有“*”或“/”不相邻,就分别计算每一块乘或除运算结果存入提前运算数组advancedOperate[]
if(indexOfOperator[i-1] != indexOfOperator[i]-1) {
advancedOperate[a] = opration(number[indexOfOperator[i-1]-1],number[indexOfOperator[i-1]],operator[indexOfOperator[i-1]]);
a++;
}
//当运算完所有需要提前运算跳出循环
if(indexOfOperator[i] == 0) {
break;
}
}
//a为数组number[]指针,b为数组operator[]指针,c为数组advancedOperate[]的指针
for(int a = 0,b = 1,c = 0;a < numberLength && b < operatorLength;) {
//如果该运算符为“*”或“/”的前一个,则后操作数传递提前运算数组中的值
if(operator[b] == '*' || operator[b] == '/') {
result = opration(result,advancedOperate[c],operator[b-1]);
c++;
a += 2;
b += 2;
}
else {
result = opration(result,number[a],operator[b-1]);
a++;
b++;
}
}
}
System.out.print(expression + "=" + result);
}
}
初学java代码还不够规范,不过确实感觉对初学者有些价值。这段代码还有不完整的地方还没解决,凑活康康。