Reputation:
I have failed to find the reason why the two strings are not equal.Here is my code:
public static void main(String[] args) {
JTextArea jt=new JTextArea();
jt.append("why \n me?"); //i set a test value to the JTextArea
Document doc = jt.getDocument();
Element root = doc.getDefaultRootElement();
Element element = root.getElement(0);
int start = element.getStartOffset();
int end = element.getEndOffset();
//the code above is what i specifically need for my app, to bring a
//specific line from a JTextArea
String s;
try {
s=doc.getText(start, end - start);
System.out.print("s = "+s);
if(s.equals("why")) //i expect equals() here to return true
System.out.print("s equals "+s);
else
System.out.print("s is not equal to "+s);
} catch (BadLocationException ex) {
ex.getStackTrace();
}
}
The result I get after running the program is:
s = why
s is not equal to why
Upvotes: 0
Views: 747
Reputation: 127
if you want to compare the content of two string object,you can use s.compareTo("why")==0
Upvotes: -1
Reputation: 718678
The most likely explanation is that the s
string is actually "why "
. Note the space character.
Indeed, if you look at the string you append to the JTextArea, there is space after "why" and before the newline.
Generally speaking, when you display a string for debugging purposes, it is a good idea to display it with quotes around it so that can notice any leading or trailing whitespace. For example:
System.out.println("s = '" + s + "'");
Another possible explanation (though unlikely in this case) is homoglyphs; i.e. two different Unicode codepoints that look like each other in a typical font.
Upvotes: 1
Reputation: 69440
If you print it out with eye catcher: System.out.print("s = >>" + s +"<<");
you see that at the end you have included the blanks and the line break:
s = >>why
<<s is not equal to why
and why \n
is not equals to why
use s = doc.getText(start, end - start).trim();
and it should work.
Upvotes: 0
Reputation: 121998
Your result must have a space as you have a space before the new line
s=doc.getText(start, end - start);
You end
is including the space before \n
. You need to write
s=doc.getText(start, (end -1) - start);
Or you can trim it while comparing as it is just space. Note that if you have someother letter other than space trim wont work.
Upvotes: 1