I am creating a program that displays the top ten game scores.
The output displays the game score and a name but in my program the names do not match with the score.
It seems that the numbers get sorted correctly - the names do get sorted with the data. The list sorts from highest to lowest. In the output it shows the highest score is:
23 "stan"
when it should show:
23 "tweak"
public class singlyLinked {
class Node {
int data;
String name;
Node next;
public Node(int data, String name) {
this.data = data;
this.name = name;
this.next = null;
}
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
}
public Node head = null;
public Node tail = null;
int size = 0;
public void addNode(int data, String name) {
Node newNode = new Node(data, name);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public void sortList() {
Node current = head;
Node index = null;
int temp;
if (head == null) {
return;
} else {
while (current != null) {
index = current.next;
while (index != null) {
if (current.data < index.data) {
temp = current.data;
current.data = index.data;
index.data = temp;
current.getName();
}
index = index.next;
}
current = current.next;
size++;
}
}
}
public void topTen() {
while (size > 10) {
if (head == null) {
return;
} else {
if (head != tail) {
Node current = head;
while (current.next != tail) {
current = current.next;
}
tail = current;
tail.next = null;
} else {
head = tail = null;
}
}
size--;
}
}
public void getSize() {
System.out.println(size);
}
public void display() {
Node current = head;
if (head == null) {
System.out.println("List is empty");
return;
}
while (current != null) {
System.out.println(current.data + current.name + " ");
current = current.next;
}
}
public static void main(String[] args) {
singlyLinked list = new singlyLinked();
System.out.println("HighScore:" + " Name:");
list.addNode(8, " stan");
list.addNode(7, " kenny");
list.addNode(13, " eric");
list.addNode(12, " wendy");
list.addNode(7, " token");
list.addNode(9, " craig");
list.addNode(1, " clyde");
list.addNode(5, " butters");
list.addNode(20, " randy");
list.addNode(1, " sharon");
list.addNode(22, " timmy");
list.addNode(23, " tweak");
list.sortList(); // sorts
list.topTen();
list.display(); // displays
}
}