I can not figure out why my unit test fails at the line,
assertTrue( (String) temp=="c+(d/f)-e");
even though when I print the content of temp serially, it is the same.
Here are the codes
Unit Test
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()=='-');
}
}
here is the class 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;
}
}
}