Skip to content

Commit 66fdf2d

Browse files
realDuYuanChaogithub-actions
andauthored
Expression evaluation (examplehub#42)
* add docs * remove whitespace * expression evaluation * Formatted with Google Java Formatter Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 05fd2f9 commit 66fdf2d

File tree

4 files changed

+67
-0
lines changed

4 files changed

+67
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.examplehub.datastructures.stack;
2+
3+
import com.examplehub.strings.RemoveWhiteSpace;
4+
5+
public class ExpressionEvaluation {
6+
7+
/**
8+
* Expression evaluation algorithms.
9+
*
10+
* @param expression the expression to be calculated.
11+
* @return result of expression.
12+
* @throws Exception if {@code expression} is invalid.
13+
*/
14+
public static int evaluate(String expression) throws Exception {
15+
16+
return PostfixEvaluation.evaluate(
17+
Infix2Postfix.infix2PostFix(RemoveWhiteSpace.removeWhitespace(expression)));
18+
}
19+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.examplehub.strings;
2+
3+
public class RemoveWhiteSpace {
4+
5+
/**
6+
* Remove all whitespace of a string.
7+
*
8+
* @param s the string to be removed whitespace.
9+
* @return string no whitespace.
10+
*/
11+
public static String removeWhitespace(String s) {
12+
return s.replaceAll(" ", "");
13+
}
14+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.examplehub.datastructures.stack;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class ExpressionEvaluationTest {
8+
9+
@Test
10+
void evaluate() throws Exception {
11+
assertEquals(5, 2 + 3);
12+
assertEquals(-1, 2 - 3);
13+
assertEquals(0, 2 / 3);
14+
assertEquals(6, 2 * 3);
15+
assertEquals(80, ExpressionEvaluation.evaluate("1+(2*3^4)/2-2"));
16+
assertEquals(80, ExpressionEvaluation.evaluate("1 + (2 * 3 ^ 4) / 2 - 2"));
17+
}
18+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.examplehub.strings;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
class RemoveWhiteSpaceTest {
8+
@Test
9+
void testRemoveWhitespace() {
10+
assertEquals("ILoveJava", RemoveWhiteSpace.removeWhitespace("I Love Java"));
11+
assertEquals("ILoveJava", RemoveWhiteSpace.removeWhitespace("I Love Java"));
12+
assertEquals(
13+
"ILoveJava", RemoveWhiteSpace.removeWhitespace(" I L ov e Ja va"));
14+
assertEquals("", RemoveWhiteSpace.removeWhitespace(" "));
15+
}
16+
}

0 commit comments

Comments
 (0)