lundi 24 août 2020

Implementation of the Postfix-Notation in Java, why does the testcase fail?

I try to implement the Postfix-Notation/ Reverse Polish Notation, for that I may use as an Import only the following class:

public class IntegerStack
 {
    public boolean emptystack();
    public int head();
    public void push(int i);
    public int pop();
}

Unfortunaetly a given Testcase fails with the following prompt:

Testcase:

IntegerStack s = new IntegerStack();
String[] input = {"1", "2", "*", "3", "4", "*", "+"};
Calculator(input, s);
System.out.println(s.compareHistory(new String[] { 
"[1]",
"[1, 2]",
"[1]",
"[]",
"[2]",
"[2, 3]",
"[2, 3, 4]",
"[2, 3]",
"[2]",
"[2, 12]",
"[2]",
"[]",
"[14]",
"[]" }
));
 // what it should be as output:

 true

// what the output is now:
wrong history length: target 14 - is 0
false

I don´t understand what this errorline "wrong history length: target 14 - is 0 false" means in this case, can anyone please explain to me what the mean and how I can fix it?

The code I´ve written so far:

public int Calculator(String[] input, IntegerStack s) 
{ s = new IntegerStack(); 
for (int i = 0; i < input.length; i++) {
switch(input[i]) {
  case "+":
    int x = s.pop();
    int y = s.pop();

      s.push(y + x);
    
    break;
  case "-":
    x = s.pop();
    y = s.pop();

      s.push(y - x);
    
    break;
  case "/":
    x = s.pop();
    y = s.pop();

      s.push(y / x);
   
    break;
  case "*":
    x = s.pop();
    y = s.pop();

      s.push(y * x);
    
    break;
  case " ":
    break;
  default:
    if (input[i] != null) {
      s.push(Integer.parseInt(input[i]));
    }
    else {
    }
    ;
  }
}

int z = s.pop();
return z;
}

Aucun commentaire:

Enregistrer un commentaire