-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculate.java
73 lines (65 loc) · 2.11 KB
/
Calculate.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.Set;
import java.util.HashMap;
import java.util.Scanner;
import java.io.IOException;
public class Calculate
{
public static void main(String[] args) throws IOException
{
Scanner userIn = new Scanner(System.in);
boolean anotherExpression = true;
while(anotherExpression)
{
String mode = "";
while(!mode.equals("p") && !mode.equals("i"))
{
System.out.print("Type p for postfix or i for infix: ");
mode = userIn.nextLine();
}
System.out.print("Please type your expression (with a single space between each token): ");
String strExpr = userIn.nextLine();
Expression expr = null;
if(mode.equals("p"))
{
expr = Expression.expressionFromPostfix(strExpr.split(" "));
}
else
{
expr = Expression.expressionFromInfix(strExpr.split(" "));
}
System.out.println("Postfix: " + expr.toPostfix());
System.out.println("Prefix: " + expr.toPrefix());
System.out.println("Infix: " + expr.toInfix());
Expression simple = expr.simplify();
System.out.println("\nSimplified: " + simple);
Set<String> variables = expr.getVariables();
HashMap<String, Integer> assignment = new HashMap<String, Integer>();
boolean anotherAssignment = true;
while(variables.size() > 0 && anotherAssignment)
{
System.out.println("\nPlease assign integer values to the variables:");
for(String v : variables)
{
System.out.print(v + " = ");
int i = userIn.nextInt();
assignment.put(v, i);
}
assignment.put("not_yet_implemented", 0);
System.out.println("\nThe expression evaluates to: " + expr.evaluate(assignment));
System.out.println("The simplified expression evaluates to: " + simple.evaluate(assignment));
System.out.print("Would you like to reassign the variables (y/n)? ");
String answer = userIn.next();
if(!answer.equalsIgnoreCase("y"))
{
anotherAssignment = false;
}
}
System.out.print("Would you like to type another expression (y/n)? ");
String answer = userIn.next();
if(!answer.equalsIgnoreCase("y"))
{
anotherExpression = false;
}
}
}
}