简体   繁体   English

我检查字符串数组是否排序的方法有什么问题

[英]What's wrong with my method that checks if an array of strings is sorted

I am doing a Java class and I cannot figure it out where I am wrong. 我在做Java类,但无法弄清楚我哪里写错了。

I have a class called ArrayMethods and a method that I must use to see if my arrays are sorted or not. 我有一个名为ArrayMethods的类,以及一个必须用来查看数组是否已排序的方法。 This is my code: 这是我的代码:

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

And then I have a tester for this arrays that goes like this: 然后我有一个用于此数组的测试器,如下所示:

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

For the first array I do get true as it is normal, the problem is that I get true for the other 2 and it is clearly that this is false. 对于第一个数组,我确实会像通常的那样得到对,问题是我对其他两个数组都对,并且显然这是错误的。 What is it that I do not get? 我不明白是什么?

could make it a little simpler by directly returning false inside of the loop 通过直接在循环内部返回false可以使操作更简单

   for (int i = 0; i < list.length - 1; i++) {
        if (list[i].compareTo(list[i + 1]) > 0) {
            return false;
        }
    }
    return true;
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 = false;
                break;

            }
        }
        return sorted;
    }
}`

You could also do it with Java 8 streams if you like their syntax (though it is not a perfect use case for them because you need two elements of the stream for your operation): 如果您喜欢Java 8流的语法,也可以使用Java 8流(尽管对于它们而言,这不是一个完美的用例,因为您需要两个流元素来进行操作):

public static boolean isSorted(final String[] array) {
    return !IntStream.range(1, array.length)
        .mapToObj(i -> new Pair<String>(array[i - 1], array[i])).parallel()
            .anyMatch(t -> t.first.compareTo(t.second) > 0);
}

The code uses a small helper class Pair 该代码使用一个小的辅助类Pair

public static final class Pair<T> {
    final T first;
    final T second;

    private Pair(final T first, final T second) {
        this.first = first;
        this.second = second;
    }
}

This solution could also run parallel which would make it faster when running on large arrays. 该解决方案还可以并行运行,这使得在大型阵列上运行时速度更快。

Credits to Collect successive pairs from a stream for accessing a Pair of elements with streams 从流中收集连续对的点数,以访问中的一对元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM