Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expression evaluation #14

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;

//import androidx.test.runner.AndroidJUnit4;

/**
* Instrumented test, which will execute on an Android device.
Expand Down
51 changes: 10 additions & 41 deletions app/src/main/java/com/exuberant/calci/HomeActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
import android.widget.TextView;
import android.widget.Toast;

import com.exuberant.calci.utility.Expression;
import com.google.android.material.button.MaterialButton;

public class HomeActivity extends AppCompatActivity implements View.OnClickListener {

private String currentNumber = "", totalCalculation = "";
private String currentEquation = "", totalCalculation = "";
private TextView totalCalculationTextView, currentAnswerTextView;

@Override
Expand Down Expand Up @@ -46,67 +47,35 @@ public void onClick(View view) {
MaterialButton button = (MaterialButton) view;
int id = button.getId();
switch (id){
//Handling all operators
case R.id.btn_addition :
case R.id.btn_division :
case R.id.btn_multiplication :
case R.id.btn_subtraction :
handleOperatorClick(button.getText().toString());
break;

//Handling clear button
case R.id.btn_clear:
currentNumber = "";
currentEquation = "";
totalCalculation = "";
break;

//Handle calculation
case R.id.btn_equals:
totalCalculation += currentNumber;
//totalCalculation += currentNumber;
calculateAnswer();
break;

//Handle other numerical button clicks
//Handle other button clicks
default:
currentNumber += button.getText().toString();
currentEquation += button.getText().toString();
}
updateDisplay();
}

private void updateDisplay(){
totalCalculationTextView.setText(totalCalculation);
currentAnswerTextView.setText(currentNumber);
}

private void handleOperatorClick(String operator){
if (!(currentNumber.equals("") || currentNumber.length() == 0)) {
totalCalculation += currentNumber + operator;
currentNumber = "";
} else {
totalCalculation = totalCalculation.substring(0, totalCalculation.length() - 1);
totalCalculation += operator;
}
}

private double add(double a, double b){
return a + b;
}

private double sub(double a, double b){
return a - b;
}

private double mul(double a, double b){
return a * b;
}

private double div(double a, double b){
return a / b;
currentAnswerTextView.setText(currentEquation);
}

private void calculateAnswer(){
//Use totalCalculation string to get final answer and display it
double answer = 0.0;
double answer = Expression.evaluateExpression(currentEquation);
totalCalculation = currentEquation;
currentEquation = String.valueOf(answer);
updateDisplay();
}
}
111 changes: 111 additions & 0 deletions app/src/main/java/com/exuberant/calci/utility/Expression.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.exuberant.calci.utility;

import java.util.Stack;

public class Expression {

public static double evaluateExpression(String expression) {
expression = infixToPostfix(expression);
String[] inputs = expression.split(" ");

Stack<Double> stack = new Stack<>();

for(int i=0; i<inputs.length; i++) {
if( isNumeric(inputs[i]) )
stack.push( Double.parseDouble(inputs[i]) );
else {
double num2 = stack.pop();
double num1 = stack.pop();

double interAns;
switch( inputs[i] ) {
case "+":
interAns = num1 + num2;
break;
case "-":
interAns = num1 - num2;
break;
case "x":
interAns = num1 * num2;
break;
case "/":
interAns = num1 / num2;
break;
default:
interAns = 0;
}

stack.push(interAns);
}
}

return stack.pop();
}

private static String infixToPostfix(String expression) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();

for(int i=0; i<expression.length(); i++) {
char c = expression.charAt(i);

if(c == ' ') continue;

if( Character.isDigit(c) || c == '.' ) {
result.append(c);
}

else if(c == '(')
stack.push(c);

else if(c == ')') {
result.append(' ');
while(!stack.isEmpty() && stack.peek() != '(')
result.append(stack.pop());

if( !stack.isEmpty() && stack.peek() != '(' )
throw new IllegalStateException();
else stack.pop();
}

else {
while(!stack.isEmpty() && priority(c) <= priority(stack.peek())) {
if(stack.peek() == '(') throw new IllegalStateException();
result.append(' ');
result.append(stack.pop());
}
result.append(' ');
stack.push(c);
}
}

while(!stack.isEmpty()) {
if(stack.peek() == '(') throw new IllegalStateException();
result.append(' ');
result.append(stack.pop());
}

return result.toString().replaceAll("\\s+", " ");
}

private static boolean isNumeric(String input) {
try {
Double.parseDouble(input);
return true;
} catch(NumberFormatException ex ) {
return false;
}
}

private static int priority(char c) {
switch(c) {
case '+':
case '-':
return 1;
case 'x':
case '/':
return 2;
}
return -1;
}
}
2 changes: 1 addition & 1 deletion app/src/main/res/layout/content_number_board.xml
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
app:layout_constraintTop_toTopOf="@+id/btn_eight" />

<com.google.android.material.button.MaterialButton
android:text="X"
android:text="x"
android:textColor="@android:color/white"
android:backgroundTint="@color/colorOperatorKey"
android:id="@+id/btn_multiplication"
Expand Down