'Java Insertion sort for an array of Scores [duplicate]
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?
Solution 1:[1]
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/
Solution 2:[2]
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nik |
| Solution 2 | ????? |
