0

我有一个程序可以检查列表是否已排序。如何打印答案?(即“列表已排序”、“列表未排序”)。

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;
}
}
4

2 回答 2

3

只需在 a 中调用方法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;
}
于 2013-09-16T12:41:33.963 回答
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");
}
于 2013-09-16T12:43:20.723 回答