【问题标题】:Can't dequeue operators from one queue to another by checking if character is an operator through a boolean method that uses switch无法通过使用 switch 的布尔方法检查字符是否是运算符,从而将运算符从一个队列出列到另一个队列
【发布时间】:2017-02-14 08:03:35
【问题描述】:
import java.util.Scanner;

public class Tester {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
char c = 'x';
Queue q1 = new Queue();
Stack s1 = new Stack();
s1.push('#');
Queue q2 = new Queue();
q1.enqueue('#');

while (c != '#') {
    System.out.println("Enter a character: ");
    c = input.next().charAt(0);
    q1.enqueue(c);
}       
while (c != '#') {
    c = (char) q1.dequeue();
    if (!operator(c)) {
        q2.enqueue(c);
    }
}
q1.print(q1);
System.out.println();
q2.print(q2);

}

public static boolean operator(char c) {
 char op = 'x';
 boolean isOperator;

 switch (op) {
 case '*':
 case '/':
 case '^':
 case '+':
 case '-':
     isOperator = true;
     break;
 default:
     isOperator = false;
     break;
}
return isOperator;
 }
}

这样做的目的是让我将一些字符输入队列 q1,然后当字符不是 # 时,它应该从 q1 出列,只要该字符不是运算符并将其入队到 q2。 但是,我的 q1 中的所有运算符都没有出队并入队 q2,这应该从第 20-23 行开始。

【问题讨论】:

    标签: java stack queue infix-notation postfix


    【解决方案1】:

    您的问题出在变量 c 中,该变量在执行第二个 while 之前未重置。

    如果您退出第一个 'while' 循环,c 将设置为 '#' 并且您不会进入第二个循环。

    试试这个:

    while (c != '#') {
        System.out.println("Enter a character: ");
        c = input.next().charAt(0);
        q1.enqueue(c);
    }       
    c = 'a'
    while (c != '#') {
        c = (char) q1.dequeue();
        if (!operator(c)) {
            q2.enqueue(c);
        }
    }
    

    【讨论】:

    • 我不认为这有帮助,因为我在代码的开头将 # 排入队列。
    • 你试过了吗?您正在检查条件中的“c”而不是 q1!
    • 是的,它仍然会打印结果,并且都保留在 q1 中。
    • 好的,我想我已经弄明白了.. 下班后会回复。
    • 问题可能是你的入队实现。这段代码中的问题只是那个。不设置c,代码不能工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2011-03-15
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 2022-07-01
    • 2014-04-13
    相关资源
    最近更新 更多