gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:59:48 25 4
gpt4 key购买 nike

我已经用“,”分割了字符串列表,然后检查了 charAt 0==1 和 charAt 0==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]) 同样会为你做。看看这个answer了解更多详情。

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

关于java - 通过比较存储为字符串列表的边值来显示三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60809455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com