I am trying to write a command line calculator
that when typed should look like something like this: C:\\java cs212.calculator.Calculator prefix + x 8 8 x 6 6
the first argument should be what notation the problem is written in. The other arguments(which can vary in number) will be the problem itself.
Here's what i need to do:
1. Take arguments from command line
2. Convert to a
string 3. Tokenize on the string
4. Feed into a queue, stack, linked list
5. use the datastructure
6. print out answer and change notaion to suffix prefix and postfix
ex)
c:>
java cs212.calculator.Calculator prefix + x 8 8 x 6 6
Prefix + x 8 8 x 6 6
Infix 8 x 8 + 6 x 6
Postfix 8 8 x 6 6 x +
100
I've done most of it except i have one really hard problem that i have no idea how to go about.
How do I convert prefix or postfix to infix especially since the problem varies in length. Oh. I decided to use a stack for a prefix notation argument because its first in last out so all i have to do is pop it contents and it should be in postfix notation.
here's what i have so far:
this is the class that takes the argument and decides where to send it:
package cs212.calculator;
public class Calculator {
String s;
PrefixStack ps;
InfixQueue iq;
public Calculator(String s) {
this.s = s;
if (s.startsWith("prefix"))
ps = new PrefixStack(s);
else if (s.startsWith("infix"))
iq = new InfixQueue(s);
else if (s.startsWith("postfix"))
System.out.println("postfix " + s);
else
System.out.println("Error: ModeOfExecutionNotFound");
}
public static void main(String[] args) {
if (args.length < 2){
System.out.println("Usage: ParametersNotMet program will terminate");
System.exit(0);
} else {
String s = args[0] + " ";
for (int i = 1;i < args.length; i++){
s += (args[i] + " ");
}
Calculator calculator1 = new Calculator(s);
}
}
}
Here is my file that takes care of a prefix:
package cs212.calculator;
import java.util.*;
public class PrefixStack {
/*variables*/
private String s;
private StringTokenizer st;
private Stack stack;
private Stack stack2;
/*constructor*/
public PrefixStack(String s) {
this.s = s;
/*intialize StringTokenizer and tokenize on String s*/
st = new StringTokenizer(s," ");
/*initialize Java DataStructure Stack, "First in Last out" */
stack = new Stack();
stack2 = new Stack();
/*push tokenz on to Stack*/
while(st.hasMoreTokens()){
stack.push(st.nextToken());
}
/**********************from here **************************/
System.out.println(s);
System.out.println(convertToSufix(s, stack));
System.out.println(convertToInfix(s, stack));
}
public String convertToSufix(String s, Stack stack){
String s2 = "Sufix ";
while(!stack.empty()){
if(stack.peek().equals("prefix")){
break;
}
s2 += (stack.pop() + " ");
}
return s2;
}
public String convertToInfix(String s, Stack stack){
String s2 = "Infix ";
return s2;
}
}
as you can see my in my convertToInfix method i have nothing going on. any help would be greatly apprecitated.
Thanks in advance.