Hallo Java_Gemeinde möchte gerne einen UPN+Rechner programmieren läuft aber noch nicht ganz so wie er soll. Der Stack sollte bis zu 256 Werte aufnehmen können. Leider merkt sich mein Stack das letzte Ergebnis nicht und ich kann daher nicht weiterrechnen. Er soll nur die Grundrechnungsarten mit ganzen Zahlen errechnen können.(int)
Code:
public class UpnRechner{
public static void main(String[] args){
String s;
String st;
Stack op = new Stack();
printHeader();
do{
int result = 0;
int count = 0;
Out.print(" Operanden eingeben: ");
st=In.readWord();
while(!st.equals("+")&&!st.equals("-")&&!st.equals("*")
&&!st.equals("/")&&!st.equals("n")){
int cnt = 0;
StringBuffer d = new StringBuffer();
for(int i=0;i<=st.length()-1;i++){
d.append(st.charAt(i));
cnt++;
}
if(d.length() > 0){
s = d.toString();
op.push((int) Double.parseDouble(s));
count++;
}
st=In.readWord();
}
if(st.equals("+")||st.equals("-")
||st.equals("*")||st.equals("/")){
count = count-1;
if(st.equals("+")){
result = op.pop() + op.pop();
}
if(st.equals("-")){
result = op.pop() - op.pop();
}
if(st.equals("*")){
result = op.pop() * op.pop();
}
if(st.equals("/")){
result = op.pop() / op.pop();
}
}
if(!st.equals("n") && count > 0){
System.out.println("Ergebnis "+result);
}
}// end of do
while(!st.equals("n"));
} // end of main
public static void printHeader(){
System.out.println(" *************************");
System.out.println(" **** STACK-RECHNER ****");
System.out.println(" *************************");
System.out.println();
System.out.println(" Operanden und anschliessend gewünschte");
System.out.println(" Rechenoperation (+,-,*,/) eingeben!");
System.out.println(" Programm mit (n) beänden ");
System.out.println();
}// end printHeader
}// End of class
Code:
class Stack{
Node top = null;
boolean underflow;
void push(int x){//pushs a double on top
Node q = new Node(x);
q.next = top;
top = q;
}
int pop(){//pops a int from top
Node p;
underflow = top == null;
if (underflow)
return -1;
p = top;
top = top.next;
return p.val;
}
}
Code:
class Node{
int val; // the stored value
Node next; // reference to next node
Node(int val){
this.val = val;
next = null;
}
}