Java 比较运算符和字符串
对于一个学校项目,的目标是构建一个编译器,尽管我已经完成了所有其他要求,我似乎无法让比较运算符处理字符串。它适用于整数、浮点数、字符和布尔值,但在处理字符串时会出现问题。在不发布全部代码的情况下,我将告诉您变量的参数正在输出正确的值 例如,这在我自己的编译器中: var测试:=“你好”=“你好” 我的函数中的参数是分别具有hello和hi值的标记Java 比较运算符和字符串,java,string,compiler-construction,operators,Java,String,Compiler Construction,Operators,对于一个学校项目,的目标是构建一个编译器,尽管我已经完成了所有其他要求,我似乎无法让比较运算符处理字符串。它适用于整数、浮点数、字符和布尔值,但在处理字符串时会出现问题。在不发布全部代码的情况下,我将告诉您变量的参数正在输出正确的值 例如,这在我自己的编译器中: var测试:=“你好”=“你好” 我的函数中的参数是分别具有hello和hi值的标记 if(type == type.STRING) { if(operator == Punctuator.Equal) { // the opera
if(type == type.STRING) {
if(operator == Punctuator.Equal) { // the operator checks which operator is used which in this case is "==", that is what Punctuator.Equal is equal to.
code.add(JumpTrue);
code.add(Jump);
}
// operator for when '!='
}
因此,这段代码所做的是查看参数是否为字符串,并且运算符是否等于“==”。然后使用编译器代码转换为机器语言,我将在下面发布一个代码片段
Jump, // takes a string operand, branches to statement with that label.
JumpFalse, // takes a string operand. Pops top value (integer) from stack, does Jump if value=0
JumpTrue, // takes a string operand. Pops the top (integer) and Jumps if it is not 0.
JumpNeg, // takes a string operand. Pops the top (integer) and Jumps if it is negative.
JumpPos, // takes a string operand. Pops the top (integer) and Jumps if it is positive.
JumpFNeg, // takes a string operand. Pops the top (floating) and Jumps if it is negative.
JumpFPos, // takes a string operand. Pops the top (floating) and Jumps if it is positive.
JumpFZero, // takes a string operand. Pops the top (floating) and Jumps if it is zero.
Call, // takes a string operand. Jumps to that location, and pushes return instruction location.
JumpV, // [... addr] -> [...] Branches to addr.
CallV, // [... addr] -> [...] Jumps to addr, and pushes return instruction location.
如果有人能看出我的错误所在,请给我一些提示,以便我能弥补
考虑到我正在处理字符串,我相信“code.add(JumpTrue)”可能不起作用,但我不知道还能用什么
编辑:我不是在使用Java编译器编译代码。这是由我自己的编译器编译的,允许通过字符串进行“==”比较。您在哪里比较字符串?您必须使用.equals进行字符串比较,而不是“==”运算符或的可能副本。为了清楚起见(对其他人来说),我不相信这是一个纯粹的
string==string
问题,因为他们似乎在实现自己的机器语言/编译器,所以输入是var test:=“hello”==“hi”然后,假设代码“编译”机器语言instructions@MadProgrammer您是对的,很抱歉造成混淆。很抱歉,我看不出这里有足够的信息供我们提供帮助。您在哪里比较字符串?您必须使用.equals进行字符串比较,而不是“==”运算符或的可能副本。为了清楚起见(对其他人来说),我不相信这是一个纯粹的string==string
问题,因为他们似乎在实现自己的机器语言/编译器,所以输入是var test:=“hello”==“hi”然后,假设代码“编译”机器语言instructions@MadProgrammer你说得对,很抱歉给你带来困惑。对不起,我看不出这里有足够的信息让我们提供帮助。