Wrong output when using if();{} in Java [closed]

You must remove the last “;” from this line:

            if(name[i].compareToIgnoreCase(name[j])>0);

this is a very common error, basically the body of the if it’s the “;” itself, i.e. the empty instruction, and the following block

            {
            tmp=name[i];
            name[i]=name[j];
            name[j]=tmp;      
            }

is always executed.
If you have an IDE with auto-format my advice is to use it extensively since it helps a lot to find this kind of errors, here how it looks after an auto-format:

    if (name[i].compareToIgnoreCase(name[j]) < 0)
      ;
    {
      tmp = name[i];
      name[i] = name[j];
      name[j] = tmp;
    }

as you can see it’s very easy to spot the error.

Leave a Comment