检查数组是否已排序 [英] Checking if an array is sorted

查看:184
本文介绍了检查数组是否已排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个程序,它接受一个整数数组作为参数并返回一个String。如果数组从最小到最大排序,字符串将是升序,如果数组从最大到最小排序,则降序,未排序是数组根本没有排序,所有相同的如果数组的所有元素都相等。

I am trying to build a program that accepts an array of integers as parameter and returns a String. The string would be "ascending" if the array is sorted from the smallest to the greatest, "descending" if the array is sorted from the greatest to the smallest, "not sorted" is the array is not sorted at all and "all the same" if all elements of the array are equal.

到目前为止,我有以下代码。我在正确的轨道上吗?我一直在下面指出的行上出现错误,说参数类型的运算符>未定义。知道是什么原因造成的吗?

So far I have the following code below. Am I on the right track? I keep getting an error on the line indicated below saying "The operator > is undefined for the argument type". Any idea what could cause it?

import java.util.*;
import java.io.*;
import java.util.Scanner;

public class arrayCheck {
    public static void main(String[] args) throws IOException {
        arrayInput();
        isSorted(null);
    }

    public static String arrayInput() {
        int size = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the size of the array: ");
        size = in.nextInt();
        System.out.println("The size you enetered is " + size);
        int[] array = new int[size];
        System.out.println("Enter the array: ");
        int j = 0;
        while (j < size) {
            System.out.print("Enter int"+ (j + 1) + ": ");
            array[j] = in.nextInt();
            ++j;
        }
        in.close();
        String arrayS = Arrays.toString(array);
        return arrayS;
    }

    public static String isSorted(String[] arrayS) {
        int n = arrayS.length;
        for (int i = 0; i < n - 1; ++i)
            if (arrayS[i] > arrayS[i + 1])   //ERROR ON THIS LINE
                return "not ascending";
        return "ascending";
    }
}


推荐答案

错误表示没有为 String 类型定义运算符> ,这是数组的元素类型。运算符< > 仅适用于 int long ,而不是对象。

The error means that the operator > is not defined for the String type, which is the element type of your arrays. The operators < and > are only usable on primitive types like int or long, not on objects.

这里你需要使用 String.compareTo ,如下所示:

Here you need to use String.compareTo instead, like this:

    if (arrayS[i].compareTo(arrayS[i+1]) > 0)

这篇关于检查数组是否已排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆