我有一个程序可以检查列表是否已排序。我该如何打印答案? (即“列表已排序”,“列表未排序”)。
public class CheckList {
public static void main(String[] args) {
int[] myList = new int[10];
// Read in ten numbers
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers: ");
for (int i = 0; i < myList.length; i++) {
myList[i] = input.nextInt();
}
}
//Check if list is sorted
public static boolean isSorted(int[] myList) {
if (myList[0] > 1) {
for (int i = 1; i < myList[0]; i++)
if (myList[i] > myList[i + 1])
return false;
}
return true;
}
}
答案 0 :(得分:3)
只需在if
:
if(isSorted(myList)) {
System.out.println("Array is sorted");
} else {
System.out.println("Array is not sorted");
}
无论如何,你的isSorted
方法不起作用,我会做这样的事情:
//checks if array is sorted in ascending order
public static boolean isSorted(int[] myList) {
if(myList == null) return false; //just checking
for (int i = 0; i < myList.length - 1; i++) {
if (myList[i] > myList[i + 1]) {
return false;
}
}
return true;
}
答案 1 :(得分:1)
只需在for loop
for (int i = 0; i < myList.length; i++) {
myList[i] = input.nextInt();
}
if(isSorted(myList)) {
System.out.println("The list is sorted");
} else {
System.out.println("The list is not sorted");
}