0

I am trying to create a program that sort five integers in ascending order. I have never ran into a dereferenced error before so I am curious what I am doing wrong.

           Scanner input = new Scanner(System.in);
        int[] a = new int[5];
        for (int i = 0; i < 5; i++) {
            System.out.println("Please enter integer # "+ 1 + i);
            int temp = input.nextInt();
            a[i] = temp;
        }


        System.out.println("Sorted from lowest to highest");


        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                int temp = a[i];
                int tempB = a[j];
                if (temp.compareTo(tempB) < 0) {
                    a[i] = tempB;
                    a[j] = temp;
                }
            }
        }

        for (int i = 0; i < 5; i++) {
            System.out.println(a[i]);
        }
    }
}

I am getting the error on this line.

if (temp.compareTo(tempB) < 0) 

Thanks!

Cory
  • 145
  • 4
  • 12
  • Special case of [java - compareTo with primitives -> Integer / int - Stack Overflow](https://stackoverflow.com/questions/9150446/compareto-with-primitives-integer-int) – user202729 Feb 19 '22 at 13:19

2 Answers2

1
temp

is of type int, which does not have methods. you should just write

if(temp < tempB)
Xirema
  • 19,889
  • 4
  • 32
  • 68
1

You can't call compareTo method on int (primitive type).

Use:

if(temp < tempB)
Wololo
  • 841
  • 8
  • 20