【发布时间】:2014-01-04 13:45:26
【问题描述】:
您好,我一直在研究我的 Java 计算器。它现在将所有操作数和运算符放在不同的数组中,并且我还有一个数组,每个运算符的优先级。
For example * and / are 1 and + and - are 2.
So if my operator array holds '[/, +, +, *]'
My priority array holds '[1, 2, 2, 1]'
我一直坚持的部分是我现在需要确保我的计算器可以重新排序运算符,以便我可以通过我的calculateResult 工作并确保运算符的顺序正确。
我寻求帮助的部分是计算结果。我不知道如何去做,以便它以正确的顺序计算它。
import java.util.*;
public class stringCalculator {
//String containing the input from the user
private String userinput;
//List to store the operators in
private ArrayList<String> calcOperator = new ArrayList<String>();
//List to store the operands in
private ArrayList<Integer> calcOperand = new ArrayList<Integer>();
//Array to store all the integers in
private String[] integers;
//Array to store all the operators in
private String[] operators;
//Array to store the priority value
private String[] priorityList;
public stringCalculator(String userinput){
this.userinput = userinput;
//System.out.println(userinput);
integers = userinput.split("[+-/*///]");
operators = userinput.split("\\d+");
}
//This function will check the input and return true if the user enters a correct expression.
public boolean checkInput(){
boolean show = userinput.matches("[-+/*0-9]+");
return show;
}
//This function will add any numbers in the string to the calcOperand array.
//and any operators to the calcOperator field.
public void parseInput(String[] item){
for (String op : item){
if (op.matches("\\d+")){
calcOperand.add(Integer.parseInt(op));
}
//operators go into calcOperators.
else if (op.equals("+")||op.equals("-")||op.equals("*")||op.equals("/")){
calcOperator.add(op);
}
else{//everything else is ignored and left.
}
}
}
//Function to calculate the priority of each operator.
//For example * and / will be 1, and + and - will be 2.
public void calculatePriority(){
priorityList = calcOperator.toArray(new String[calcOperator.size()]);
for (int i = 0; i<priorityList.length; i++){
if (priorityList[i].equals("+")){
priorityList[i] = "2";
}else if (priorityList[i].equals("-")) {
priorityList[i] = "2";
}else if (priorityList[i].equals("/")){
priorityList[i] = "1";
}else if (priorityList[i].equals("*")){
priorityList[i] = "1";
}else{
System.out.println("error");
}
}
}
public void printPri(){
for (String s : priorityList)
System.out.print(s +",");
}
//Function to show the result of the expression.
public void calculateResult(){
if(checkInput()){
parseInput(integers);
parseInput(operators);
System.out.println("Operands: " + calcOperand);
System.out.println("Operators: " + calcOperator);
calculatePriority();
System.out.print("Priority: ");
printPri();
}else{
System.out.println("Please enter a valid input!");
}
}
}
【问题讨论】:
标签: java arrays string calculator