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";
}
}
The error means that the operator
>is not defined for theStringtype, which is the element type of your arrays. The operators<and>are only usable on primitive types likeintorlong, not on objects.Here you need to use
String.compareToinstead, like this: