0

I have split the list of strings by "," and then checked the charAt 0==1 and charAt 0==2 then equilateral triangle....so on, but i am getting none of these for all, while debugging i can see the charAt 0 and charAt 1 are equal bt the entire evaluation is false.


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

}
}

Please explain me whats going on here...

2 Answers2

1

When comparing Strings in Java (and, more generally, objects) with the "==" operator, what is compared is not the characters of the Strings but their reference. If the two objects are not the very same object, "==" returns false

Here, you should modify your for loop this way:

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


}

For Strings, the .equals function compares the characters in the strings rather than their references.

William A.
  • 425
  • 5
  • 14
1

I see two issues in your program:

  1. As already pointed out, == compares the reference which is not reliable in your case of string comparision, it is also not the recommended way you compare strings in Java, index[0].equals(index[1]) and likewise would do it for you. Look at this answer for more details.

  2. In the 'Isoceles' control statement, you need to have additional conditions like this: index[0].equals(index[1]) || index[1].equals(index[2]) || index[0].equals(index[2])

sgX
  • 696
  • 1
  • 8
  • 16