-2

I am new to Java and trying Insertion sort an array of Score which is from a text file. The text file has only a String name and int score value. I tried with the following code below:

public static void insertionSort(Score[] scores)
    {
        for(int i = 1; i < scores.length; i++)
        {
            int temp = scores[i];
            int j = i - 1;
            while(j >= 0 && scores[j] > temp)
            {
                scores[j + 1] = scores[j];
                j--;
            }
            scores[j + 1] = temp;
        }
    }

The error says that Scores cannot be converted to Int. How do I solve this issue?

Xam0110
  • 11
  • 2
  • 1
    If `scores` is an array of Score objects, why is `temp` an int? Also you cannot use `<` on your objects: you will need some way of comparing them, such as the `Comparable` interface. – khelwood Apr 13 '22 at 08:10
  • I picked that "duplicate" question because it gives you one specific example how to go about such things. The key point here: java is a typed language. A Score or String or Scanner object ... is not a primitive int value, thus you can't compare such objects to int values. – GhostCat Apr 13 '22 at 08:20

2 Answers2

0

Your method signature tells me that the method is expecting scores is an array of Score Objects. You are accessing a Score object instance via the array but using the value as if it were an int value which is not true.

Check the Score class which methods it has.

Another tip: I'd suggest letting java do the sort and keep the data as is. This means if there is a new score, just append it. If you want it sorted then use java built ins.

You can see here how it works:

https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/

Nik
  • 172
  • 7
0

Score is a Object,so it cannot be converted to Int.Its property is Int,You can use it like this:

class Score{
    /**
     * your Score Object,hava a value called num
     */
    private int num;

    public int getNum() {
        return num;
    }
}

public static void insertionSort(Score[] scores)
{
    for(int i = 1; i < scores.length; i++)
    {
        Score score = scores[i];
        int j = i - 1;
        while(j >= 0 && scores[j].getNum() > score.getNum())
        {
            scores[j + 1] = scores[j];
            j--;
        }
        scores[j + 1] = score;
    }
}