You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何跳过空白字符实现前缀表达式转后缀功能

前缀转后缀程序空白字符跳过实现方案

问题描述

实现前缀表达式向后缀表达式转换的程序时,若输入表达式存在意外空白字符(例:正确表达式为$+-ABC+D-EF,异常输入为$+-ABC+D-E F)程序会运行异常,需要结合返回布尔值的isBlank方法,通过if-else分支实现跳过空白字符、读取下一个有效字符的逻辑,当前代码中isBlank判断分支未编写处理逻辑。

修复步骤

  • 优化isBlank方法:原有方法仅能识别半角空格,补充制表符、换行、回车、全角空格等常见空白字符的判断,避免空白字符被误识别为操作数压入栈。
  • 补全isBlank分支逻辑:当判断当前字符为空白时,执行continue语句直接跳过当前轮次循环,自动进入下一轮遍历读取下一个字符,不对空白字符做任何栈操作。

现有for循环结构下isBlank分支留空也会自动进入下一轮循环,但显式编写continue语义更明确,可避免后续循环新增通用逻辑时误处理空白字符。

修复后完整代码

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 ' ':    // 半角空格
            case '\t':   // 水平制表符
            case '\n':   // 换行符
            case '\r':   // 回车符
            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-- ){
            char currentChar = prefix_exp.charAt(i);
            if (isOperator(currentChar)){

                // 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 + currentChar;

                // Push the result back onto the stack
                expression_stack.push(temp);
            }

            else if(isBlank(currentChar)){
                // 跳过空白字符,直接进入下一轮循环
                continue;
            }

            // If the symbol is an operand
            else {
                // Push the operand onto the stack
                expression_stack.push(currentChar + "");
            }
        }

        return expression_stack.peek();
    }
}

内容的提问来源于stack exchange,提问作者ka177

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 10:09:46