我未能找到两个字符串不相等的原因。这是我的代码:
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();
}
}
运行程序后得到的结果是:
s = why
s is not equal to why
最佳答案
您的结果必须有一个空格,因为新行之前有一个空格
s=doc.getText(start, end - start);
您end
包含\n
之前的空格。你需要写
s=doc.getText(start, (end -1) - start);
或者您可以在比较时修剪它,因为它只是空格。 请注意,如果您有除空格之外的其他字母,修剪将不起作用。
关于java - 对于两个相等的字符串,Equals() 不返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43869535/