gpt4 book ai didi

java - 为什么没有 split ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:28:24 27 4
gpt4 key购买 nike

我很困惑为什么它不拆分字符串?当我调试时,我的字符串 exp 数组不包含任何内容,这是拆分错误吗?我想做的是拆分一个非常简单的表达式,如 1+2+3,然后解析值,做一个计算器。

编辑嗨,为什么我要拆分每个字符是因为我在做一个计算器,并且已经阅读了一些关于将中缀转换为后缀的内容,所以我需要拆分字符串然后循环遍历每个字符串并进行如下所示的检查,但是当我调试时它显示 exp[] 是空的

For each token in turn in the input infix expression:

* If the token is an operand, append it to the postfix output.
* If the token is an operator A then:
o While there is an operator B of higher or equal precidence than A at the top of the stack, pop B off the stack and append it to the output.
o Push A onto the stack.
* If the token is an opening bracket, then push it onto the stack.
* If the token is a closing bracket:
o Pop operators off the stack and append them to the output, until the operator at the top of the stack is a opening bracket.
o Pop the opening bracket off the stack.

When all the tokens have been read:

* While there are still operator tokens in the stack:
o Pop the operator on the top of the stack, and append it to the output.


// the main class
public class Main {


public static void main(String[] args) {
calcExpChecker calc = new calcExpChecker("1+2+3+4");
calc.legitExp();
calc.displayPostfix();
}

}
//the class
package javaapplication4;
import java.util.*;


public class calcExpChecker {


private String originalExp; // the orginal display passed
private boolean isItLegitExp; // the whole expression is it legit
private boolean isItBlank; // is the display blank?
private StringBuilder expression = new StringBuilder(50);
private Stack stack = new Stack();//stack for making a postfix string

calcExpChecker(String original)
{
originalExp = original;
}

//check for blank expression
public void isitBlank()
{
if(originalExp.equals(""))
{
isItBlank = true;
}
else
{
isItBlank = false;
}

}

//check for extra operators
public void legitExp()
{
String[] exp = originalExp.split(".");
for(int i = 0 ; i < exp.length ; i++)
{
if(exp[i].matches("[0-9]"))
{
expression.append(exp[i]);
}
else if(exp[i].matches("[+]"))
{
if(stack.empty())
{
stack.push(exp[i]);
}
else
{
while(stack.peek().equals("+"))
{
expression.append(stack.pop());
}
stack.push(exp[i]);
}
}
if (!stack.empty())
{
expression.append(stack.pop());
}
}

}

public void displayPostfix()
{
System.out.print(expression.toString());
}
}

最佳答案

如果你让每个字符都是分隔符,那么它们之间是什么?没有

例如,1+2+3+41是分隔符吗?是的,好的,捕获它和下一个分隔符之间的所有内容。下一个分隔符? +。什么都没拍到。下一个分隔符? 2.等等等等

关于java - 为什么没有 split ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3346442/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com