I am working on a program that converts a prefix to a postfix expression. However, when there is an unexpected blank space in an expression such as "$ -ABC D-E F" instead of "$ -ABC D-EF" the program doesn't work correctly. How do I write skip to the next character and ignore the whitespace, trying to do it through an if else statement using a boolean isBlank method.
public class PrefixConverter{
// Checks if character is an operator
public boolean isOperator(char c){
switch (c){
case ' ':
case '-':
case'*':
case'/':
case'$':
return true;
}
return false;
}
// Ignores white space
public boolean isBlank(char c){
switch (c){
case ' ':
return true;
}
return false;
}
// Method to convert Prefix expression to Postfix expression
public String preToPost (String prefix_exp){
// Create a new stack with length of the prefix string
int size = prefix_exp.length();
Stack expression_stack = new Stack (size);
// Read expression from right to left
for (int i = size -1; i >=0 ; i-- ){
if (isOperator(prefix_exp.charAt(i))){
// Pop two operands from the stack
String op1 = expression_stack.peek();
expression_stack.pop();
String op2 = expression_stack.peek();
expression_stack.pop();
// Concatenate the operands and the operator
String temp = op1 op2 prefix_exp.charAt(i);
// Push the result back onto the stack
expression_stack.push(temp);
}
else if(isBlank(prefix_exp.charAt(i))){
// Skip to next character
}
// If the symbol is an operand
else {
// Push the operand onto the stack
expression_stack.push(prefix_exp.charAt(i) "");
}
}
return expression_stack.peek();
}
}
CodePudding user response:
One way would be to write a continue;
in this else if():
else if(isBlank(prefix_exp.charAt(i))){
// Skip to next character
continue;
}
continue will simply move to the next iteration of the loop
However, if you do not need the spaces you can remove them from the prefix_exp String in the beginning by doing this:
prefix_exp = prefix_exp.replaceAll("\\s", "");
Just make sure you do the replaceAll before you call .length() of the String as the size changes.
CodePudding user response:
Just use the continue
statement to skip to the end of your for loop.
This will trigger the loop to run with the next character. But since the rest of your code is in if statements anyway, your code should behave well by just doing nothing.
...
else if(isBlank(prefix_exp.charAt(i))){
// Skip to next character
continue;
}
See also https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html