Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Source Code] HighScoreList class
Index -> Programming, Java -> Java Submissions
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Aziz




PostPosted: Mon Jun 27, 2005 1:34 am   Post subject: [Source Code] HighScoreList class

Hey I wrote this yesterday and today. Got the idea from my Turing module, but this ones kinda different Razz Java makes it easy. Tell me what you think and what I could do to make it better. I'll be posting a test class up soon but right now I NEED SLEEEEEEEEEEP *DROOL* Goodnight Smile

code:
/* The "HighscoreList" class
 * Creates a highscore list for a game
 * with names and scores.
 * Scores can be added (automatticaly sorted)
 * You can get an array of scores, or a single score
 * Also different methods like clearing the list, getting the size of it, etc.
 */
 
 import java.io.*;
 
 public class HighScoreList
 {
        //Default size and file name constants
        protected final int SIZE = 5;
        protected final String FILE_NAME = "highscore.dat";
        
        //Size of the highscore list (number of entries)
        protected int size;
        
        //The file name
        protected String fileName;
        
        //Scores and names arrays
        protected int scores[];
        protected String names[];
        
        ////////////////
        //CONSTRUCTORS//
        ////////////////
        
        //Constructor that set size and filename to defaults
        public HighScoreList() throws IOException
        {
               //Set size and file name
               size = SIZE;
               fileName = FILE_NAME;
               
               //Set size of scores and names array;
               scores = new int[size + 1];
               names = new String[size + 1];
               
               //File object
               File file = new File(fileName);
               
               //Checks to see if the file specified is an already existing file
               //Or if we need to make a new one.
               if (file.exists())
               {
                      //Get the names and scores into the lists
                      readScores();
               } else
               {
                       //Create file
                       createFile();
                       
                       //Set all the objects' scores arrays to blanks
                       for (int i = 0; i < scores.length - 1; i++)
                       {
                              scores[i] = 0;
                              names[i] = "---";
                       }
               }
        }
        
        //Constructor that sets size to specified and filename to default
        //Will only read the first [dSize] scores
        public HighScoreList(int dSize) throws IOException
        {
               //Set size and file name
               size = dSize;
               fileName = FILE_NAME;
               
               //Set size of scores and names array;
               scores = new int[size + 1];
               names = new String[size + 1];
               
               //File object
               File file = new File(fileName);
               
               //Checks to see if the file specified is an already existing file
               //Or if we need to make a new one.
               if (file.exists())
               {
                      //Get the names and scores into the lists
                      readScores();
               } else
               {
                       //Create file
                       createFile();
                       
                       //Set all the objects' scores arrays to blanks
                       for (int i = 0; i < scores.length - 1; i++)
                       {
                              scores[i] = 0;
                              names[i] = "---";
                       }
               }
        }
        
        //Constructor that sets filename to specified and size to default
        public HighScoreList(String dFileName) throws IOException
        {
               //Set size and file name
               size = SIZE;
               fileName = dFileName;
               
               //Set size of scores and names array;
               scores = new int[size + 1];
               names = new String[size + 1];
               
               //File object
               File file = new File(fileName);
               
               //Checks to see if the file specified is an already existing file
               //Or if we need to make a new one.
               if (file.exists())
               {
                      //Get the names and scores into the lists
                      readScores();
               } else
               {
                       //Create file
                       createFile();
                       
                       //Set all the objects' scores arrays to blanks
                       for (int i = 0; i < scores.length - 1; i++)
                       {
                              scores[i] = 0;
                              names[i] = "---";
                       }
               }
        }
        
        //Constructor that set size and filename to specified
        //Will only read the first [dSize] scores
        public HighScoreList(int dSize, String dFileName2) throws IOException
        {
               //Set size and file name
               size = dSize;
               fileName = dFileName2;
               
               //Set size of scores and names array;
               scores = new int[size + 1];
               names = new String[size + 1];
               
               //File object
               File file = new File(fileName);
               
               //Checks to see if the file specified is an already existing file
               //Or if we need to make a new one.
               if (file.exists())
               {
                      //Get the names and scores into the lists
                      readScores();
               } else
               {
                       //Create file
                       createFile();
                       
                       //Set all the objects' scores arrays to blanks
                       for (int i = 0; i < scores.length - 1; i++)
                       {
                              scores[i] = 0;
                              names[i] = "---";
                       }
               }
        }
        
        /////////////
        //PROTECTED//
        /////////////
        
        //Bubble Sort (sorts according to scores and places names with)
        protected void sort()
        {
               //Temporary variables
               int tempScore;   //Temporary score
               String tempName;              //Temporary name
               
               //Sorted flag
               boolean sorted = true;
               
               //Continue sorted until the list is sorted
               do
               {
                      //Reset flag
                      sorted = true;
                      
                      //Check and sort
                      for (int i = 0; i < scores.length - 1; i++)
                      {
                             if (scores[i] < scores[i+1])
                             {
                                    //Swap scores
                                    tempScore = scores[i+1];
                                    scores[i+1] = scores[i];
                                    scores[i] = tempScore;
                                    
                                    //Swap names
                                    tempName = names[i+1];
                                    names[i+1] = names[i];
                                    names[i] = tempName;
                                    
                                    //Flag not sorted
                                    sorted = false;
                             }
                      }
                      
               } while (!sorted);     
        }
        
        //Creates the highscore file, settings names to "---" and scores to 0
        protected void createFile() throws IOException
        {
               //New PrintWriter to output to highscore file
               PrintWriter output = new PrintWriter(new FileWriter(fileName));
               
               //Write as many blank entries as needed
               for (int i = 0; i < scores.length - 1; i++)
               {
                      output.println("---" + "#" + 0 + "$");
               }
               
               //Close stream
               output.close();
        }
        
        //Reads the scores to local array
        protected void readScores() throws IOException
        {
               //New BufferedReader to get the scores from the highscore list
               BufferedReader input = new BufferedReader(new FileReader(fileName));
               
               //Temporary input line
               String tempLine;
               char tempChLine[]; //Array of characters
               
               //Temporary score string
               String scoreStr;
               
               //Counting variable
               int j;
               
               //Read first line
               tempLine = input.readLine();
               
               //Write as many blank entries as needed
               for (int i = 0; i < scores.length - 1; i++)
               {
                      //Set the array of characters to line read from file
                      tempChLine = tempLine.toCharArray();
                      
                      //Clear string
                      scoreStr = "";
                      names[i] = "";
                      
                      //Reset counting variable
                      j = 0;
                      
                      //Add the characters to name until marker #
                      while (tempChLine[j] != '#')
                      {
                             names[i] += tempChLine[j];
                             j++;
                      }
                      
                      j++;
                      
                      //Add the characters to score string until marker $
                      while (tempChLine[j] != '$')
                      {
                             scoreStr += tempChLine[j];
                             j++;
                      }
                      
                      //Add integer value of scoreStr to score
                      scores[i] = Integer.parseInt(scoreStr);
                      
                      //Read next line
                      tempLine = input.readLine();
               }
               
               //Close stream
               input.close(); 
        }
        
        //Writes list of scores to file
        protected void writeScores() throws IOException
        {
               //New PrintWriter to output to highscore file
               PrintWriter output = new PrintWriter(new FileWriter(fileName));
               
               //Write the scores
               for (int i = 0; i < scores.length - 1; i++)
               {
                      output.println(names[i] + "#" + scores[i] + "$");
               }
               
               //Close stream
               output.close();
        }
        
        //////////
        //PUBLIC//
        //////////
        
        //Adds the specified score (w/ name) to the list and writes it to file
        public void addScore(String name, int score) throws IOException
        {
               //Add the score and its name to end of array
                names[size] = name;
                scores[size] = score;
               
                //Sorts them in
                sort();
        }
        
        //Clears the highscore file (basically same as createFile(), but user can user it
        public void clearList() throws IOException
        {
               //New PrintWriter to output to highscore file
               PrintWriter output = new PrintWriter(new FileWriter(fileName));
               
               //Write as many blank entries as needed
               for (int i = 0; i < scores.length - 1; i++)
               {
                      output.println("---" + "#" + 0 + "$");
               }
               
               //Close stream
               output.close();
        }
        
        //Returns the size of the highscore list
        public int getSize()
        {
               return size;
        }
        
        //Returns the list of names
        public String[] getNames()
        {
               return names;
        }      
        
        //Returns the list of scores
        public int[] getScores()
        {
               return scores;
        }
        
        //Returns top score holder's name
        public String getTopScoreHolder()
        {
               return names[1];
        }
        
        //Returns top score holder's score
        public int getTopScore()
        {
               return scores[1];
        }
        
        //Returns specified highscore holder's name
        //(returns error msg if value over list size)
        public String getScoreHolder(int place)
        {
               if (place < size)
               {
                      return names[place];
               } else
               {
                      return "Invalid place";
               }
        }
        
        //Returns specified highscore holder's score
        //(returns -1 if value over list size)
        public int getScore(int place)
        {
               if (place < size)
               {
                      return scores[place];
               } else
               {
                      return -1;
               }
        }
 }



The Extension 'class' was deactivated by an board admin, therefore this Attachment is not displayed.


HighScoreList.java
 Description:

Download
 Filename:  HighScoreList.java
 Filesize:  8.76 KB
 Downloaded:  272 Time(s)

Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Mon Jun 27, 2005 1:40 am   Post subject: (No subject)

Now rewrite it much shorter by subclassing something like ArrayList. Smile
Aziz




PostPosted: Mon Jun 27, 2005 9:37 am   Post subject: (No subject)

If I knew how and new what subclassing mean I would Laughing
*Still java n00b*
wtd




PostPosted: Mon Jun 27, 2005 2:37 pm   Post subject: (No subject)

I'm talking about inheritance. "Is a" relationships. Code reuse. Smile

You're creating a list class, right? So each object of that class is going to be a list. Well, we already have basic list classes, so why not inherit from those and get all of the list functionality "for free"?

Consider a simple example: my classic Name class.

Java:
class Name
{
   private String first, last;

   public Name(String f, String l)
   {
      first = f;
      last = l;
   }

   public String getFirst() { return first; }
   public String getLast() { return last; }

   public String fullName()
   {
      return first + " " + last;
   }
}


Now, what if I want a name class that has a title? We'll call it "FormalName". Well, I would copy and paste and write an entirely new class.

Java:
class Name
{
   private String title, first, last;

   public Name(String t, String f, String l)
   {
      title = t;
      first = f;
      last = l;
   }

   public String getTitle() { return title; }
   public String getFirst() { return first; }
   public String getLast() { return last; }

   public String fullName()
   {
      return title + " " + first + " " + last;
   }
}


Or, I could use inheritance and make FormalName a subclass of Name.

Java:
class FormalName extends Name
{
   private String title;

   public FormalName(String t, String f, String l)
   {
      super(f, l);
      title = t;
   }

   public String getTitle() { return title; }

   public String fullName()
   {
      return title + " " + super.fullName();
   }
}


Now, to take this a bit further...

Java:
class DoctorsName extends FormalName
{
   public FormalName(String f, String l)
   {
      super("Dr.", f, l);
   }
}


And now since a FormalName is a Name, anywhere I have a method that takes a Name as a parameter, I can give it a FormalName, or a DoctorsName.
Aziz




PostPosted: Mon Jun 27, 2005 3:03 pm   Post subject: (No subject)

Would that be possible for this? My highscore list has 2 lists...names and scores, or is there another way, oh great Dark Master?
wtd




PostPosted: Mon Jun 27, 2005 3:15 pm   Post subject: (No subject)

Presumably each score is connected to a name. Create a HighScoreRecord class.

(Java 1.4.2)

Java:
class HighScoreRecord implements Comparable
{
   private String name;
   private int score;

   public HighScoreRecord(String n, int s)
   {
      name = n;
      score = s;
   }

   public String getName() { return name; }
   public int getScore() { return score; }

   public int compareTo(Object o)
   {
      HighScoreRecord other = (HighScoreRecord)o;

      int scoreComparison = new Integer(score).compareTo(new Integer(other.getScore()));
      int nameComparison = name.compareTo(other.getName());

      if (scoreComparison == 0)
      {
         return nameComparison;
      }
      else
      {
         return scoreComparison;
      }
   }
}


Now you can just have a single list of those. Smile
Aziz




PostPosted: Mon Jun 27, 2005 3:41 pm   Post subject: (No subject)

Awesome, I'm going to try that later. And actually try to understand it, instead of just copy and paste it. But not right now. I'm going to go play some Xbox. Thanks a bunch.

Oh and one more question. How do you get the java code tags? Instead of just:

code:

     !CODE!

Thanks Smile
wtd




PostPosted: Mon Jun 27, 2005 3:50 pm   Post subject: (No subject)

code:
[syntax="java"]blah blah blah[/syntax]
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Java -> Java Submissions
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 8 Posts ]
Jump to:   


Style:  
Search: