Reputation: 43
OK, so I am writing a console calculator and I am stuck. I have everything working but the actual part where a user enters say 3*2+8 and then the program tell the user the answer. I can, however, enter a single number like 3 and it return 3.0. I think I need to parse the expression entered by the user to perform the math. Can you help me?
public static void main(String[] args) {
String input = ""; // initalize the string
boolean isOn = true; // used for the while loop...when false, the program will exit.
String exitCommand = "Exit"; // exit command
System.out.print("Enter a math problem"); // dummy test
Scanner keyboard = new Scanner(System.in);
//input = keyboard.nextLine();
String[] token = input.split(("(?<=[-+*/])|(?=[-+*/])"));
while (isOn) {
for (int i = 0; i < token.length; i++) {
//System.out.println(token[i]);
Double d = Double.parseDouble(keyboard.nextLine()); //This causes an error
//String[] token = d.split(("(?<=[-+*/])|(?=[-+*/])"));
//input = keyboard.nextLine();
if (input.equalsIgnoreCase(exitCommand)) {
// if the user enters exit(ignored case) the boolean goes to false, closing the application
isOn = false;
}
System.out.print(token[0] + d); // shows the math problem(which would by the end of the coding should show the
//answer to the entered math problem.
}
}
}
public void validOperator() {
ArrayList<String> operator = new ArrayList<String>();
operator.add("+");
operator.add("-");
operator.add("*");
operator.add("/");
}
public void validOperands(){
ArrayList<String> operand = new ArrayList<String>();
operand.add("0");
operand.add("1");
operand.add("2");
operand.add("3");
operand.add("4");
operand.add("5");
operand.add("6");
operand.add("7");
operand.add("8");
operand.add("9");
}
}
Thanks
Upvotes: 1
Views: 1059
Reputation:
You do not take in account the precedence of math operators. And what if a user will use brackets, like (2 + 3) * 4 + 5/2
I recommend to convert the initial expression to the postfix notation before evaluating it.
Here is the example with explanation for C++, I think it will be easy to apply this explanation to the java language.
Upvotes: 1