1

I'm trying to make a program that processes a line of rpn expression through a stack method. The input is a string array that is converted from a string input.

String[] collect = "8 6 + 2 /"; //the
String line; //the inputed line
collect = line.split(" "); //the conversion
System.out.println(stackem(collect)); // calling the stack method for an output method

The problem is that the output is always the operator ate the end of the line, so when I put in the code that checks for malformed expressions it always turns into the error. Basically my input would be like this:
input: 8 6 + 2 /
output: Error: "Expression is malformed"
output (without the error code): /
output (what's supposed to be the output): 7

This is the code for the stack method:

public String stackem(String[] input)
{
Stack<String> stack = new Stack<String>();
int x, y;
String result = "";
int get = 0;
String choice;
int value = 0;
String p = "";
int output;

try
{
for (int i = 0; i < input.length; i++) 
{
if (input[i] == "+" || input[i] == "-" || input[i] == "*" || input[i] == "/" || input[i] == "^") 
{
choice = input[i];
}
else 
{
stack.push(input[i]);
continue;
}

switch (choice) 
{
case "+":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x + y;
result = p + value;
stack.push(result);
break;

case "-":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y - x;
result = p + value;
stack.push(result);
break;

case "*":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = x * y;
result = p + value;
stack.push(result);
break;

case "/":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = y / x;
result = p + value;
stack.push(result);
break;

case "^":
x = Integer.parseInt(stack.pop());
y = Integer.parseInt(stack.pop());
value = (int)Math.pow(y,x);
result = p + value;
stack.push(result);
break;

default:
continue;
}
}

output = Integer.parseInt(stack.pop());
}
catch (Exception ex)
{
return "Error: Expression is malformed";
}
return "Result: " + output;
}

Is there any way to fix this issue?

0 Answers0