Hi I have been working on my Java calculator. It now puts all the operands and operators in different arrays and I also have an array with the priority of each operator.
For example * and / are 1 and + and - are 2.
So if my operator array holds '[/, +, +, *]'
My priority array holds '[1, 2, 2, 1]'
The part I have come stuck on is I now need to make sure my calculator can reorder the operators so I can work through my calculateResult and make sure the operators are in the correct order.
The part I am asking for help with is calculate result. I cant figure out how to go about doing this so that it calculates it in the correct order.
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!");
}
}
}