【发布时间】:2016-02-15 03:56:26
【问题描述】:
如果String.length()不能用来比较两个String对象并确定哪个对象更大,那么什么字符串方法会做这样的事情呢?当我运行此代码时,它会立即终止。有没有比较字符串对的方法?我在这里使用字符串类的 API 作为参考:https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
public class ThingsComparer {
public static void main(String[] args) {
String ObjectOne = new String("One");
String ObjectTwo = new String("Two");
if (ObjectOne.length() > ObjectTwo.length())
{
System.out.println("ObjectOne is larger");
}
else if (ObjectOne.length() < ObjectTwo.length())
{
System.out.println("ObjectTwo is larger");
}
else if (ObjectOne.equals(ObjectTwo))
{
System.out.println("ObjectOne and ObjectTwo are equal");
}
}
}
【问题讨论】:
-
你的意思是更长还是更大?
-
可以在doc页面看到
compareTo的方法,为什么不用呢?如果这不是您要查找的内容,则必须更清楚地了解更大的含义? -
是的,我指的是长度,所以我认为更长的措辞是正确的
-
第三个 if 语句比较的是字符串,而不是它们的长度。你的代码是正确的,
-
是的,这就是我想要的。谢谢
标签: java string object compare string-comparison