Alex Simion Alex Simion - 3 months ago 13
Java Question

What's wrong with my method that checks if an array of strings is sorted

I am doing a Java class and I cannot figure it out where I am wrong.

I have a class called ArrayMethods and a method that I must use to see if my arrays are sorted or not. This is my code:

public class ArrayMethods
{
String[] list; //instance variable
/**
* Constructor for objects of class ArrayMethods
*/
public ArrayMethods(String[] list)
{
// initialise instance variables
this.list = list;
}

/**
* Determines if the array is sorted (do not sort)
* When Strings are sorted, they are in alphabetical order
* Use the compareTo method to determine which string comes first
* You can look at the String compareTo method in the Java API
* @return true if the array is sorted else false.
*/
public boolean isSorted()
{
boolean sorted = true;

// TODO: Write the code to loop through the array and determine that each
// successive element is larger than the one before it
for (int i = 0; i < list.length - 1; i++){
if (list[i].compareTo(list[i + 1]) < 0){
sorted = true;

}
}
return sorted;
}
}


And then I have a tester for this arrays that goes like this:

public class ArrayMethodsTester{
public static void main(String[] args){
//set up
String[] animals = {"ape", "dog", "zebra"};
ArrayMethods zoo = new ArrayMethods(animals);

//test isSorted
System.out.println(zoo.isSorted());
System.out.println("Expected: true");

String[] animals2 = {"ape", "dog", "zebra", "cat"};
zoo = new ArrayMethods(animals2);
System.out.println(zoo.isSorted());
System.out.println("Expected: false");

String[] animals3 = {"cat", "ape", "dog", "zebra"};
zoo = new ArrayMethods(animals3); ;
System.out.println(zoo.isSorted());
System.out.println("Expected: false");
}
}


For the first array I do get true as it is normal, the problem is that I get true for the other 2 and it is clearly that this is false. What is it that I do not get?

Answer

could make it a little simpler

   for (int i = 0; i < list.length - 1; i++) {
        if (list[i].compareTo(list[i + 1]) > 0) {
            return false;
        }
    }
    return true;
Comments