Skip to content
Merged
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
@@ -0,0 +1,19 @@
package com.examplehub.datastructures.stack;

import com.examplehub.strings.RemoveWhiteSpace;

public class ExpressionEvaluation {

/**
* Expression evaluation algorithms.
*
* @param expression the expression to be calculated.
* @return result of expression.
* @throws Exception if {@code expression} is invalid.
*/
public static int evaluate(String expression) throws Exception {

return PostfixEvaluation.evaluate(
Infix2Postfix.infix2PostFix(RemoveWhiteSpace.removeWhitespace(expression)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@
import java.util.Stack;

public class Infix2Postfix {

/**
* Convert infix to postfix.
*
* @param infixExpression the infix expression.
* @return postfix expression.
* @throws Exception if infix expression is invalid.
*/
public static String infix2PostFix(String infixExpression) throws Exception {
if (!BalancedParentheses.isBalanced(infixExpression)) {
throw new Exception("invalid expression");
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/com/examplehub/strings/RemoveWhiteSpace.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.examplehub.strings;

public class RemoveWhiteSpace {

/**
* Remove all whitespace of a string.
*
* @param s the string to be removed whitespace.
* @return string no whitespace.
*/
public static String removeWhitespace(String s) {
return s.replaceAll(" ", "");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.examplehub.datastructures.stack;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class ExpressionEvaluationTest {

@Test
void evaluate() throws Exception {
assertEquals(5, 2 + 3);
assertEquals(-1, 2 - 3);
assertEquals(0, 2 / 3);
assertEquals(6, 2 * 3);
assertEquals(80, ExpressionEvaluation.evaluate("1+(2*3^4)/2-2"));
assertEquals(80, ExpressionEvaluation.evaluate("1 + (2 * 3 ^ 4) / 2 - 2"));
}
}
16 changes: 16 additions & 0 deletions src/test/java/com/examplehub/strings/RemoveWhiteSpaceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.examplehub.strings;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

class RemoveWhiteSpaceTest {
@Test
void testRemoveWhitespace() {
assertEquals("ILoveJava", RemoveWhiteSpace.removeWhitespace("I Love Java"));
assertEquals("ILoveJava", RemoveWhiteSpace.removeWhitespace("I Love Java"));
assertEquals(
"ILoveJava", RemoveWhiteSpace.removeWhitespace(" I L ov e Ja va"));
assertEquals("", RemoveWhiteSpace.removeWhitespace(" "));
}
}