【问题标题】:display triangle by comparing values of sides stored as a list of strings通过比较存储为字符串列表的边值来显示三角形
【发布时间】:2020-03-23 07:32:28
【问题描述】:

我已将字符串列表拆分为“,”,然后检查了 charAt 0==1 和 charAt 0==2 然后是等边三角形....等等,但我没有得到所有这些,而调试我可以看到 charAt 0 和 charAt 1 是相等的 bt 整个评估是错误的。


    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);

}
}

请解释一下这里发生了什么...

【问题讨论】:

  • Java 中的字符串与 equals 函数进行比较 ;)

标签: java string list algorithm


【解决方案1】:

我在您的程序中发现了两个问题:

    1234563 .查看此answer 了解更多详情。
  1. 在 'Isoceles' 控制语句中,您需要有这样的附加条件:index[0].equals(index[1]) || index[1].equals(index[2]) || index[0].equals(index[2])

【讨论】:

    【解决方案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 函数比较字符串中的字符而不是它们的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 2011-01-01
      • 2014-02-20
      • 2012-06-11
      • 1970-01-01
      相关资源
      最近更新 更多