我试图调用一个方法,该方法包含对if / else语句中的其他两个方法的调用。我希望用户的输入指示调用哪个方法。 if / else语句中的方法在它们不在语句内部时起作用。当我从if / else语句中调用它们时,不返回任何内容,程序结束。谁知道为什么?
以下是方法:
public String infixpostfix(String inf){
boolean spellcheck = false;
String type = null;
String result = null;
Scanner scan = new Scanner(System.in);
System.out.println("Is your input \"postfix\" or \"infix\"");
type = scan.nextLine();
while (spellcheck == false){
if (type.equals("infix")||type.equals("postfix")){
spellcheck = true;
continue;
}
else
System.out.println("Please enter a valid option. \"postfix\" or \"infix\"");
type = scan.nextLine();
}
if (type .equals("infix")){
result = postfix(inf);
System.out.println("The postfix is: ");
}
else if (type.equals("postfix")){
result = infix(inf);
System.out.println("The infix is: ");
}
return result;
}
这是Main方法(它在同一个程序中):
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
MyStack ugh = new MyStack();
System.out.println("Enter the equation");
String inf = scan.nextLine();
ugh.infixpostfix(inf);
}
}
输入样本 - 输出:
Enter the equation
ab*+
Is your input "postfix" or "infix"
postfix
The infix is:
以下是此实例中调用的方法:
public String infix(String inf){
//a + b * c + ( d * e + f ) * g
//into postfix. A correct answer is a b c * + d e * f + g * +
MyStack<String> holder2 = new MyStack();
String inf2 = inf.replaceAll("\\s+","");
int equationindex = 0;
String eq = null;
for (int infindex = 0; infindex < inf2.length(); infindex++){
boolean operand = false;
if (Character.isDigit(inf2.charAt(infindex))||Character.isLetter(inf2.charAt(infindex))){
operand = true;
}
if (operand == true){
holder2.push(Character.toString(inf2.charAt(infindex)));
continue;
}
else {
String temp2 = holder2.pop();
String temp = holder2.pop();
eq = ("(" + temp + inf2.charAt(infindex) + temp2 + ")");
holder2.push(eq);
continue;
}
}
return eq;
}
答案 0 :(得分:1)
您没有打印出结果。
更改
System.out.println("The postfix is: ");
到
System.out.println("The postfix is: " + result);
并为中缀做同样的事。