Hey! So I figured out storing the scores in a file and putting them in an array. Then sorting it and displaying the top 5 on the screen.
I am having a problem where it's not sorting through ALL from the file and everytime someone plays, their recent score gets added to the leaderboard and kicks out the top score or any other score.
The sorting seems fine but not sure how to fix the problem. Any help is appreciated
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.io.*; import java.util.ArrayList; import java.util.Scanner; /** * Write a description of class Highscores here. * * @author (your name) * @version (a version number or a date) */ public class Highscores extends Actor { public Highscores() { GreenfootImage img = new GreenfootImage(500, 500); setImage(img); } ArrayList <Integer> highscores = new ArrayList <Integer>(); public int n; /** * Act - do whatever the Highscores wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { highscore(highscores); display(highscores); } public void highscore(ArrayList highscores) { try { Scanner output = new Scanner (new File ("highscores.txt")); for (int i = 0; i < 5; i++) { highscores.add(0); //initializes the array with 5 zero's } while (output.hasNext()) { //adds highscores to an arraylist from a file highscores.add(output.nextInt()); } int i = 0; if (highscores.size() > 5) { while (highscores.size() != 5) { //while loop removes highscores if there are more than 5 highscores highscores.remove(i); } } sort(highscores, highscores.size()); } catch(IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } } public static void sort(ArrayList <Integer> highscores, int n) { // Base case if (n <= 1) return; // Sort first n-1 elements sort(highscores, n-1 ); // Insert last element at its correct position // in sorted array. int last = highscores.get(n-1); int j = n-2; /*Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while ((j >= 0) && (highscores.get(j) < last)) { highscores.set(j+1, highscores.get(j)); j--; } highscores.set(j+1, last); } public void display(ArrayList highscores) { GreenfootImage img = getImage(); img.clear(); Font f = new Font("Invasion2000", false, false, 60); img.setFont(f); img.setColor(Color.WHITE); img.drawString("" + highscores.get(0), 250, 50); img.drawString("" + highscores.get(1), 250, 150); img.drawString("" + highscores.get(2), 250, 250); img.drawString("" + highscores.get(3), 250, 350); img.drawString("" + highscores.get(4), 250, 450); setImage(img); } }