已排序/未排序 - 如何将答案打印到控制台



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

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

只需在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;
}

只需在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");
}

最新更新