Hello community,
I have an issued converting a arithmetic string called the infix, into a prefix output. In one of my methods i have an infinite loop. An example would be (a + b) * (c - d)===> * + a b - c d Here is my code:
public static String inToPrefix(String s){
Stack<Character> operator = new Stack<>();
Stack<String> operand = new Stack<>();
String output = "";
for (int i = 0; i < s.length(); i++)
{
char chValue = s.charAt(i);
if((isDigit(chValue))||(isAlpha(chValue))){
operand.push("" + chValue);
}
else if(chValue == '('){
operator.push(chValue);
}
else if(isOperator(chValue)){
while(!operator.isEmpty())
{
System.out.print("1");
if(priority(operator.peek())> priority(chValue))
{
String op = "" + operator.pop();
String Righthand = operand.pop();
String Lefthand = operand.pop();
operand.push(op + Lefthand + Righthand);
}
else{
operator.push(chValue);
}
}
operator.push(chValue);
}
else if(chValue ==')'){
while((operator.peek()!='(')&&(!operator.isEmpty())){
String op = ""+ operator.pop();
String Righthand = operand.pop();
String Lefthand = operand.pop();
operand.push(op + Lefthand + Righthand);
}
if(operator.peek() != '('){
operator.pop();
}
}
}
while(!operator.isEmpty()){
String op = "" + operator.pop();
String Righthand = operand.pop();
String Lefthand = operand. pop();
operand.push(op+ Lefthand + Righthand);
output = operand.pop();
System.out.print("1");
}
return output;
}
public static boolean isDigit(char ch){
String operators = "0123456789";
if (operators.indexOf(ch) != -1)
return true;
else
return false;
}
public static boolean isAlpha(char ch){
String operators = "abcdefghijklmnopqrstuvwxyz";
String Cap_oper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if ((operators.indexOf(ch) != -1)||(Cap_oper.indexOf(ch)!= -1)){
return true;
}
return false;
}
public static boolean isOperator(char ch){
String operators = "+-*/%";
if (operators.indexOf(ch) != -1){
return true;
}
return false;
}
public static int priority(char op){
int x;
switch(op){
case '+':
case '-':
x = 1;
break;
case '*':
case '/':
x = 2;
break;
default:
x = 0;
break;
}
return x;
}
}