我正在做一個Java類,我無法弄清楚我錯在哪裏。我的方法有什麼問題,檢查一個字符串數組是否排序
我有一個名爲ArrayMethods的類以及我必須用來查看數組是否已排序的方法。這是我的代碼:
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;
}
}
然後我對這個數組即是這樣一個測試:
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");
}
}
對於第一陣列我得到真正的,因爲它是正常的,問題是,我對其他兩個人都是正確的,顯然這是錯誤的。我沒有得到什麼?
'sorted'始終是'真',因爲你永遠不指定'FALSE'它。 – talex
您是否嘗試過[調試您的方法](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)? –