Question: For this project, you must implement a program that can evaluate simple math expressions like: 2 + 5 * ( 1 0 - 4 )

For this project, you must implement a program that can evaluate simple math expressions like: 2+5*(10-4)/6. Note that to keep things simple, the math expressions will always have a single space before and after each operator and parenthesis.
e, and if so, then it should extract and return that token.
Otherwise, it should return null.
Remember that the most powerful feature of a high-level programming language (like Java) is the ability to name things. Here we are naming the code that gets the next token, so that any time we want to get the next token, we can simply say getNextToken(myScanner). Never underestimate the power of breaking programs down into simple methods and giving your methods descriptive names that say what they do.
Now refactor your evaluateExpression method to use the getNextToken method. Then run and test your code to ensure that it still behaves as before.
Step 01.4- Write methods to determine the token type
Note that each token in one of our math expressions is either a number or an operator. For each token in the expression, we need to be able to determine its type (number or operator) so that we can process the token correctly. For this, we will write two methods.
isNumber(String) : boolean
Write a public static method that will take a single String argument (a token) and it will return true if the token is a number, otherwise, it will return false.
One of the simplest ways to do this in Java is to try and parse the String token to a double using the Double.parseDouble method. This method will throw a NumberFormatException if the parse fails. We can use try and catch blocks to catch the exception if it is thrown. So, if we try to Double.parseDouble(theToken), and a NumberFormatException is thrown, we can catch the exception and we can simply return false because the token cannot be a number if it could not be parsed to a double. On the other hand, if no exception is thrown, then the token is a number, because the parse succeeded, and we can return true.
isOperator(String) : boolean
Now write a public static method that will take a single String argument (a token) and it will return true if the token is an operator (+,-,*, and /), otherwise, it will return false. One of the simplest ways to do this in Java is the use the String contains method. For example "+-*/".contains(token) will return true if the String token

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!