Making a calculator project in java [2020]
In this post, I am gonna tell you how can you create a calculator in java, our
calc program will support every mathematical expression from user input, such as 3+5*5(7+9)^ 9.
Making Strategies to code our calc program
-
Our program will run continuously until the user enters an "/exit" command.
so for that, we will use while loop. - If the user enters an invalid Exp then we will print out "Invalid Exp".
-
To Calculate the result efficiently we'll change the Input expression
From Infix to
Postfix notation (read this in infix to postfix post) - At last, we will print out the result and wait for the next input.
Code Structure
import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String userInput; while(true) { userInput = scanner.nextLine().trim(); if(userInput.equals("/exit")) { break; } else { infixToPostfix(userInput); } } }// You'll implement these methods bellowstatic String infixToPostfix(String infixExp) {
return "this method will return postfix exp";} static Integer result(String postfixExp) { return 0; }
Read this post if you don't know about infix and postfix notation,
then come back
then come back
Implementation of infix to postFix method
In our program,
infix to postfix method takes a String type argument as infixExp and returns its
corresponding postfixExp as String. see the implementation below.
infix to postfix method takes a String type argument as infixExp and returns its
corresponding postfixExp as String. see the implementation below.
you can see I have defined a new method operator precedence, which returns
the priority order for the operators. The implementation of that method
Is done by using a switch statement. This method helps the infix to postfix method in converting in notation.
Is done by using a switch statement. This method helps the infix to postfix method in converting in notation.
static String infixToPostfix(String infixExp) {
final Stack<Character>
stack = new Stack<>();
stack = new Stack<>();
String postfix = "";
//Remove all
spaces
spaces
infixExp =
infixExp.replaceAll(" *", "");
infixExp.replaceAll(" *", "");
// Make a char array from
infixExp,
infixExp,
for (final char ch :
infixExp.toCharArray()) {
infixExp.toCharArray()) {
if(Character.isDigit(ch))
postfix += ch;
else if
(stack.isEmpty()) {
(stack.isEmpty()) {
stack.push(ch);
postfix += "
";
";
}
else if ( ch == '(' )
stack.push(ch);
else if( ch == ')' )
{
{
while(
!stack.isEmpty() && stack.peek() != '(' ) {
!stack.isEmpty() && stack.peek() != '(' ) {
postfix
+= " " + stack.pop();
+= " " + stack.pop();
}
stack.pop();
}
else if (operatorPrecedence(ch) >
operatorPrecedence(stack.peek())) {
operatorPrecedence(stack.peek())) {
stack.push(ch);
postfix += "
";
";
}
else postfix += " " +
stack.pop();
stack.pop();
}
while (!stack.isEmpty())
{
{
postfix += " " +
stack.pop();
stack.pop();
}
return postfix;
}
static short operatorPrecedence(final
char ch) {
char ch) {
switch (ch) {
case '+':
case '-': return
1;
1;
case '*':
case '/': return
2;
2;
case '^': return
3;
3;
default:
return 0;
}
}
Implementation of result method
Again I have made another additional method (arithmeticOP) to help the result
method. this method is also using a switch statement.
method. this method is also using a switch statement.
static Double result(final String postfixExp) {
final
String[] items = postfixExp.split(" ");
String[] items = postfixExp.split(" ");
final
Stack<Double> stack = new Stack<>();
Stack<Double> stack = new Stack<>();
for(final String item : items) {
if (item.matches("\d+"))
stack.push(Double.valueOf(item));
else {
final Double y = stack.pop();
final Double x = stack.pop();
stack.push(arithmeticOP(x, y, item));
}
}
return
stack.pop();
stack.pop();
}
static Double
arithmeticOP(final Double x, final Double y, final String op) {
arithmeticOP(final Double x, final Double y, final String op) {
switch
(op) {
(op) {
case "+": return x + y;
case "-": return x - y;
case "*": return x * y;
case "/": return x / y;
case "^": return Math.pow(x, y);
default: return 0.0;
}
}
}
Complete code
Please comment if anything was wrong