通过比较存储为字符串列表的边的值来显示三角形



我用","分割了字符串列表,然后检查了charAt 0==1和charAt 2==2,然后是等边三角形。。。。等等,但我根本没有得到这些,在调试时,我可以看到charAt 0和charAt 1是相等的,但整个评估都是错误的。


public static void main(String[] args) {
List<String> triangleToy=Arrays.asList("36 36 36","3 3 3","2 4 2");
List<String> toRet= new ArrayList<String>();
// TODO Auto-generated method stub
for (String s : triangleToy) {
String[] index=s.split(" ");
if((index[0]==(index[1]))&&(index[0]==(index[2]))){
toRet.add("Equilateral");
}
else if(index[0]==(index[1])){
toRet.add("Isosceles");
}
else{
toRet.add("None of these");
}

}
System.out.println(toRet);
}
}

请给我解释一下这里发生了什么。。。

我在您的程序中看到两个问题:

  1. 如前所述,==比较在字符串比较中不可靠的引用,这也不是在Java、index[0].equals(index[1])中比较字符串的推荐方法,同样也会为您进行比较。查看此答案以了解更多详细信息。

  2. 在"等腰"控制语句中,您需要具有如下附加条件:index[0].equals(index[1]) || index[1].equals(index[2]) || index[0].equals(index[2])

将Java中的字符串(以及更普遍的对象(与"=="运算符进行比较时,所比较的不是字符串的字符,而是它们的引用。如果两个对象不是同一个对象,"=="返回false

在这里,你应该这样修改你的for循环:

for (String s : triangleToy) {
String[] index=s.split(" ");
if((index[0].equals(index[1]))&&(index[0].equals(index[2]))){
toRet.add("Equilateral");
}
else if(index[0].equals(index[1])){
toRet.add("Isosceles");
}
else{
toRet.add("None of these");
}

}

对于字符串,.equals函数比较字符串中的字符,而不是它们的引用。

最新更新