gpt4 book ai didi

java - 即使正确识别了每个字符,使用 junit 比较字符串也不会断言为 true

转载 作者:行者123 更新时间:2023-12-01 23:11:49 25 4
gpt4 key购买 nike

我不明白为什么我的单元测试失败了,

assertTrue( (String) temp=="c+(d/f)-e");

即使我连续打印 temp 的内容,它也是一样的。

这是代码

单元测试

import static org.junit.Assert.*;

import org.junit.Test;


public class LexerTest {


@Test
public void testGetInExpression(){
//------
Lexer lex=new Lexer("a+b*(c+(d/f)-e)-g");
//--This test passes
assertTrue((String)lex.getLexStr()=="a+b*(c+(d/f)-e)-g");
//------

for(int i=0;i<5;i++){
lex.getNext();
}

//----------------
//Method returns a in-expression (or a substring within first parantheses)
Lexer sub=lex.getInExpression();
String temp=sub.getLexStr(); //returns a type String
System.out.println(temp);
System.out.println(temp.length());

//printing out each character of 'temp'
for(int i=0;i<temp.length();i++){
System.out.print(i);
System.out.print(" = ");
System.out.println(temp.charAt(i));
//prints: the string
// 0 = c
// 1 = +
// ...
// ..
// 8 = e
}

//The following fails (mysteriously!!)
assertTrue( (String) temp=="c+(d/f)-e");
//assertTrue( (Character)lex.getNext()=='-');
}
}

这是 Lexer 类:

public class Lexer {
private int size;
private int posn;
private String lexStr;

public Lexer(String val){
lexStr=val;
size=lexStr.length();
posn=0;
}

public String getLexStr(){
return lexStr;
}
public Object getNext(){
posn=posn+1;
if(posn<size){return current();} //return character at next site
else {return null;} //return a null value to indicate end
};

public Object current(){
if(posn<size){
char c=lexStr.charAt(posn);
if(Character.isDigit(c)){
return Character.getNumericValue(c); //return an Integer object
}else
return c; //Return a plain character
}
else{
return null;
}
};

public Lexer getInExpression(){
//This must return a subExpression in the original Expression enclosed by braces
int open=1;
int closed=0;
String returnStr=null;
String temp=lexStr.substring(posn);
for(int a=0; a <temp.length(); a++){
getNext();
if(temp.charAt(a)=='('){
open++;
}else if(temp.charAt(a)==')'){
closed++;
if(open==closed){
returnStr=temp.substring(0,a);
break;
}
}
}
//---check for validity of returnStr
if (returnStr==null){
System.out.println("I cannot be null! Please check here");
return null;
}else{
Lexer inExpr=new Lexer(returnStr);
return inExpr;
}


}
}

最佳答案

您应该使用assertEquals,而不是assertTrue。对于不同的 String 对象,使用 == 进行比较并不好。

关于java - 即使正确识别了每个字符,使用 junit 比较字符串也不会断言为 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21814990/

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