【发布时间】:2016-08-31 12:36:50
【问题描述】:
我正在做一个 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");
}
}
对于第一个数组,我确实得到了正确的结果,因为它是正常的,问题是我对其他 2 个得到了正确的结果,很明显这是错误的。我没有得到什么?
【问题讨论】:
-
sorted始终是true,因为您从未将false分配给它。
标签: java arrays sorting arraylist