SlideShare a Scribd company logo
1 of 11
Download to read offline
/*
We will be making 4 classes:
Main - for testing the code
HighscoreManager - to manage the high-scores
HighscoreComparator - I will explain this when we get there
Score - also this I will explain later
all this classes will be in the package "highscores"/*
//The Score Class
package highscores;
import java.io.Serializable;
public class Score implements Serializable {
private int score;
private String naam;
public int getScore() {
return score;
}
public String getNaam() {
return naam;
}
public Score(String naam, int score) {
this.score = score;
this.naam = naam;
}
}/*This class makes us able to make an object (an arraylist in our case) of the type Score that
contains the name and score of a player.
We implement serializable to be able to sort this type./*
//The ScoreComparator Class
package highscores;
import java.util.Comparator;
public class ScoreComparator implements Comparator {
public int compare(Score score1, Score score2) {
int sc1 = score1.getScore();
int sc2 = score2.getScore();
if (sc1 > sc2){
return -1;
}else if (sc1 < sc2){
return +1;
}else{
return 0;
}
}
}
/*This class is used to tell Java how it needs to compare 2 objects of the type score.
-1 means the first score is greater than the 2nd one, +1 (or you can just put 1) means it's smaller
and 0 means it's equal./*
//The HighscoreManager Class
/*First we will be making the HighscoreManager Class, this class will do the most important part
of the high-score system.
We will be using this as our base for the class:/*
package highscores;
import java.util.*;
import java.io.*;
public class HighscoreManager {
// An arraylist of the type "score" we will use to work with the scores inside the class
private ArrayList scores;
// The name of the file where the highscores will be saved
private static final String HIGHSCORE_FILE = "scores.dat";
//Initialising an in and outputStream for working with the file
ObjectOutputStream outputStream = null;
ObjectInputStream inputStream = null;
public HighscoreManager() {
//initialising the scores-arraylist
scores = new ArrayList();
}
}
/*I have added comments to explain what's already in the class.
We will be using a binary file to keep the high-scores in, this will avoid cheating.
To work with the scores we will use an arraylist. An arraylist is one of the great things that java
has and it's much better to use in this case than a regular array.
Now we will add some methods and functions./*
public ArrayList getScores() {
loadScoreFile();
sort();
return scores;
}
/*This is a function that will return an arraylist with the scores in it. It contains calls to the
function loadScoreFile() and sort(), these functions will make sure you have the scores from your
high-score file in a sorted order. We will be writing these functions later on./*
private void sort() {
ScoreComparator comparator = new ScoreComparator();
Collections.sort(scores, comparator);
}
/*This function will create a new object "comparator" from the class ScoreComparator.
the Collections.sort() function is in the Java Collections Class (a part of java.util). It allows you
to sort the arraylist "scores" with help of "comparator"./*
public void addScore(String name, int score) {
loadScoreFile();
scores.add(new Score(name, score));
updateScoreFile();
}
/*This method is to add scores to the scorefile.
Parameters "name" and "score" are given, these are the name of the player and the score he
had.
First the scores that are allready in the high-score file are loaded into the "scores"-arraylist.
Afther that the new scores are added to the arraylist and the high-score file is updated with it.*/
public void loadScoreFile() {
try {
inputStream = new ObjectInputStream(new FileInputStream(HIGHSCORE_FILE));
scores = (ArrayList) inputStream.readObject();
} catch (FileNotFoundException e) {
System.out.println("[Laad] FNF Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("[Laad] CNF Error: " + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
}
}
}
/*This function will load the arraylist that is in the high-score file and will put it in the
"scores"-arraylist.
The try-catch structure will avoid that your program crashes when there is something wrong
while loading the file (like when the file is corrupted or doesn't exist)./*
public void updateScoreFile() {
try {
outputStream = new ObjectOutputStream(new FileOutputStream(HIGHSCORE_FILE));
outputStream.writeObject(scores);
} catch (FileNotFoundException e) {
System.out.println("[Update] FNF Error: " + e.getMessage() + ",the program will try and
make a new file");
} catch (IOException e) {
System.out.println("[Update] IO Error: " + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
System.out.println("[Update] Error: " + e.getMessage());
}
}
}
/*This is about the same as loadScoreFile(), but instead of reading the file it will be writing the
"score"-arraylist to the file./*
public String getHighscoreString() {
String highscoreString = "";
Static int max = 10;
ArrayList scores;
scores = getScores();
int i = 0;
int x = scores.size();
if (x > max) {
x = max;
}
while (i < x) {
highscoreString += (i + 1) + ".t" + scores.get(i).getNaam() + "tt" +
scores.get(i).getScore() + " ";
i++;
}
return highscoreString;
}
/*Depending on how you want to display your highscores this function can be either usefull or
not usefull. But I have put it in here anyway.
It can be used for both console and GUI (in GUI you can put the high-score string into a label).
The function will only have the top 10 players but you can adjust the variable "max" to change
that./*
/*The Main Class
This class is just to test out the code and it shows you how you can implement it into your own
game./*
package highscores;
public class Main {
public static void main(String[] args) {
HighscoreManager hm = new HighscoreManager();
hm.addScore("Bart",240);
hm.addScore("Marge",300);
hm.addScore("Maggie",220);
hm.addScore("Homer",100);
hm.addScore("Lisa",270);
System.out.print(hm.getHighscoreString());
}
}
/*First you have to create an object from the HighscoreManager class, we will call it "hm" in
here.
Afther that you can add scores by using the .addScore() method. The first parameter has to be
the name of your player and the 2nd one is the highscore (as an int).
You can print the getHighscoreString function to get the highscore in String-format and display
them on the console with System.out.print()
Note: the first time you run you will get a "FNF Error", this means that the program hasn't
found the highscore-file, this is logical because we haven't created that, but you don't have to
worry, Java will create one itself, so afther the first time you won't have the error anymore. /*
Solution
/*
We will be making 4 classes:
Main - for testing the code
HighscoreManager - to manage the high-scores
HighscoreComparator - I will explain this when we get there
Score - also this I will explain later
all this classes will be in the package "highscores"/*
//The Score Class
package highscores;
import java.io.Serializable;
public class Score implements Serializable {
private int score;
private String naam;
public int getScore() {
return score;
}
public String getNaam() {
return naam;
}
public Score(String naam, int score) {
this.score = score;
this.naam = naam;
}
}/*This class makes us able to make an object (an arraylist in our case) of the type Score that
contains the name and score of a player.
We implement serializable to be able to sort this type./*
//The ScoreComparator Class
package highscores;
import java.util.Comparator;
public class ScoreComparator implements Comparator {
public int compare(Score score1, Score score2) {
int sc1 = score1.getScore();
int sc2 = score2.getScore();
if (sc1 > sc2){
return -1;
}else if (sc1 < sc2){
return +1;
}else{
return 0;
}
}
}
/*This class is used to tell Java how it needs to compare 2 objects of the type score.
-1 means the first score is greater than the 2nd one, +1 (or you can just put 1) means it's smaller
and 0 means it's equal./*
//The HighscoreManager Class
/*First we will be making the HighscoreManager Class, this class will do the most important part
of the high-score system.
We will be using this as our base for the class:/*
package highscores;
import java.util.*;
import java.io.*;
public class HighscoreManager {
// An arraylist of the type "score" we will use to work with the scores inside the class
private ArrayList scores;
// The name of the file where the highscores will be saved
private static final String HIGHSCORE_FILE = "scores.dat";
//Initialising an in and outputStream for working with the file
ObjectOutputStream outputStream = null;
ObjectInputStream inputStream = null;
public HighscoreManager() {
//initialising the scores-arraylist
scores = new ArrayList();
}
}
/*I have added comments to explain what's already in the class.
We will be using a binary file to keep the high-scores in, this will avoid cheating.
To work with the scores we will use an arraylist. An arraylist is one of the great things that java
has and it's much better to use in this case than a regular array.
Now we will add some methods and functions./*
public ArrayList getScores() {
loadScoreFile();
sort();
return scores;
}
/*This is a function that will return an arraylist with the scores in it. It contains calls to the
function loadScoreFile() and sort(), these functions will make sure you have the scores from your
high-score file in a sorted order. We will be writing these functions later on./*
private void sort() {
ScoreComparator comparator = new ScoreComparator();
Collections.sort(scores, comparator);
}
/*This function will create a new object "comparator" from the class ScoreComparator.
the Collections.sort() function is in the Java Collections Class (a part of java.util). It allows you
to sort the arraylist "scores" with help of "comparator"./*
public void addScore(String name, int score) {
loadScoreFile();
scores.add(new Score(name, score));
updateScoreFile();
}
/*This method is to add scores to the scorefile.
Parameters "name" and "score" are given, these are the name of the player and the score he
had.
First the scores that are allready in the high-score file are loaded into the "scores"-arraylist.
Afther that the new scores are added to the arraylist and the high-score file is updated with it.*/
public void loadScoreFile() {
try {
inputStream = new ObjectInputStream(new FileInputStream(HIGHSCORE_FILE));
scores = (ArrayList) inputStream.readObject();
} catch (FileNotFoundException e) {
System.out.println("[Laad] FNF Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("[Laad] CNF Error: " + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
System.out.println("[Laad] IO Error: " + e.getMessage());
}
}
}
/*This function will load the arraylist that is in the high-score file and will put it in the
"scores"-arraylist.
The try-catch structure will avoid that your program crashes when there is something wrong
while loading the file (like when the file is corrupted or doesn't exist)./*
public void updateScoreFile() {
try {
outputStream = new ObjectOutputStream(new FileOutputStream(HIGHSCORE_FILE));
outputStream.writeObject(scores);
} catch (FileNotFoundException e) {
System.out.println("[Update] FNF Error: " + e.getMessage() + ",the program will try and
make a new file");
} catch (IOException e) {
System.out.println("[Update] IO Error: " + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
System.out.println("[Update] Error: " + e.getMessage());
}
}
}
/*This is about the same as loadScoreFile(), but instead of reading the file it will be writing the
"score"-arraylist to the file./*
public String getHighscoreString() {
String highscoreString = "";
Static int max = 10;
ArrayList scores;
scores = getScores();
int i = 0;
int x = scores.size();
if (x > max) {
x = max;
}
while (i < x) {
highscoreString += (i + 1) + ".t" + scores.get(i).getNaam() + "tt" +
scores.get(i).getScore() + " ";
i++;
}
return highscoreString;
}
/*Depending on how you want to display your highscores this function can be either usefull or
not usefull. But I have put it in here anyway.
It can be used for both console and GUI (in GUI you can put the high-score string into a label).
The function will only have the top 10 players but you can adjust the variable "max" to change
that./*
/*The Main Class
This class is just to test out the code and it shows you how you can implement it into your own
game./*
package highscores;
public class Main {
public static void main(String[] args) {
HighscoreManager hm = new HighscoreManager();
hm.addScore("Bart",240);
hm.addScore("Marge",300);
hm.addScore("Maggie",220);
hm.addScore("Homer",100);
hm.addScore("Lisa",270);
System.out.print(hm.getHighscoreString());
}
}
/*First you have to create an object from the HighscoreManager class, we will call it "hm" in
here.
Afther that you can add scores by using the .addScore() method. The first parameter has to be
the name of your player and the 2nd one is the highscore (as an int).
You can print the getHighscoreString function to get the highscore in String-format and display
them on the console with System.out.print()
Note: the first time you run you will get a "FNF Error", this means that the program hasn't
found the highscore-file, this is logical because we haven't created that, but you don't have to
worry, Java will create one itself, so afther the first time you won't have the error anymore. /*

More Related Content

Similar to We will be making 4 classes Main - for testing the code Hi.pdf

Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginsearchbox-com
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docxalfred4lewis58146
 
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfplease navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfaioils
 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docxAdamq0DJonese
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfARORACOCKERY2111
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
Use arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdfUse arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdffootworld1
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming ConceptsBhushan Nagaraj
 
You can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenYou can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenanitramcroberts
 
Class loader basic
Class loader basicClass loader basic
Class loader basic명철 강
 

Similar to We will be making 4 classes Main - for testing the code Hi.pdf (20)

Tutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component pluginTutorial on developing a Solr search component plugin
Tutorial on developing a Solr search component plugin
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Inheritance
InheritanceInheritance
Inheritance
 
Manual tecnic sergi_subirats
Manual tecnic sergi_subiratsManual tecnic sergi_subirats
Manual tecnic sergi_subirats
 
PAGE 1Input output for a file tutorialStreams and File IOI.docx
PAGE  1Input output for a file tutorialStreams and File IOI.docxPAGE  1Input output for a file tutorialStreams and File IOI.docx
PAGE 1Input output for a file tutorialStreams and File IOI.docx
 
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfplease navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Java session4
Java session4Java session4
Java session4
 
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator-   import j.docx----------Evaluator-java---------------- package evaluator-   import j.docx
----------Evaluator-java---------------- package evaluator- import j.docx
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdfSummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
SummaryHW6 Account ManagementIn HW4, you kept track of multiple.pdf
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
3 j unit
3 j unit3 j unit
3 j unit
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
Use arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdfUse arrays to store data for analysis. Use functions to perform the .pdf
Use arrays to store data for analysis. Use functions to perform the .pdf
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
 
You can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commenYou can look at the Java programs in the text book to see how commen
You can look at the Java programs in the text book to see how commen
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 

More from anithareadymade

#include stdio.hint main() {     int count;     FILE myFi.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdf#include stdio.hint main() {     int count;     FILE myFi.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdfanithareadymade
 
ITs both by the way... it depends on the situatio.pdf
                     ITs both by the way... it depends on the situatio.pdf                     ITs both by the way... it depends on the situatio.pdf
ITs both by the way... it depends on the situatio.pdfanithareadymade
 
I believe you are correct. The phase transfer cat.pdf
                     I believe you are correct. The phase transfer cat.pdf                     I believe you are correct. The phase transfer cat.pdf
I believe you are correct. The phase transfer cat.pdfanithareadymade
 
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdfThere are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdfanithareadymade
 
The correct statements are1. the oxygen atom has a greater attrac.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdfThe correct statements are1. the oxygen atom has a greater attrac.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdfanithareadymade
 
This is a bit complex to answer as we have HCl and NaOH present, the.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdfThis is a bit complex to answer as we have HCl and NaOH present, the.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdfanithareadymade
 
The possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdfThe possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdfanithareadymade
 
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdfThe answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdfanithareadymade
 
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdfRainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdfanithareadymade
 
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdfby taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdfanithareadymade
 
import java.util.; public class DecimalToBinary { public stat.pdf
import java.util.; public class DecimalToBinary { public stat.pdfimport java.util.; public class DecimalToBinary { public stat.pdf
import java.util.; public class DecimalToBinary { public stat.pdfanithareadymade
 
i did not get itSolutioni did not get it.pdf
i did not get itSolutioni did not get it.pdfi did not get itSolutioni did not get it.pdf
i did not get itSolutioni did not get it.pdfanithareadymade
 
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdfHello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdfanithareadymade
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfanithareadymade
 
Following are the changes mentioned in bold in order to obtain the r.pdf
Following are the changes mentioned in bold in order to obtain the r.pdfFollowing are the changes mentioned in bold in order to obtain the r.pdf
Following are the changes mentioned in bold in order to obtain the r.pdfanithareadymade
 
During meiosis, each member of a pair of genes tends to be randomly .pdf
During meiosis, each member of a pair of genes tends to be randomly .pdfDuring meiosis, each member of a pair of genes tends to be randomly .pdf
During meiosis, each member of a pair of genes tends to be randomly .pdfanithareadymade
 
B parents marital statusSolutionB parents marital status.pdf
B parents marital statusSolutionB parents marital status.pdfB parents marital statusSolutionB parents marital status.pdf
B parents marital statusSolutionB parents marital status.pdfanithareadymade
 
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdfANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdfanithareadymade
 
Array- Arrays is a collection of data items with same data type and.pdf
Array- Arrays is a collection of data items with same data type and.pdfArray- Arrays is a collection of data items with same data type and.pdf
Array- Arrays is a collection of data items with same data type and.pdfanithareadymade
 

More from anithareadymade (20)

#include stdio.hint main() {     int count;     FILE myFi.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdf#include stdio.hint main() {     int count;     FILE myFi.pdf
#include stdio.hint main() {     int count;     FILE myFi.pdf
 
MgO = 2416 = 1.5 .pdf
                     MgO = 2416 = 1.5                               .pdf                     MgO = 2416 = 1.5                               .pdf
MgO = 2416 = 1.5 .pdf
 
ITs both by the way... it depends on the situatio.pdf
                     ITs both by the way... it depends on the situatio.pdf                     ITs both by the way... it depends on the situatio.pdf
ITs both by the way... it depends on the situatio.pdf
 
I believe you are correct. The phase transfer cat.pdf
                     I believe you are correct. The phase transfer cat.pdf                     I believe you are correct. The phase transfer cat.pdf
I believe you are correct. The phase transfer cat.pdf
 
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdfThere are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
There are 7 stages in Software Development LifeCycle. Coming to SDLC.pdf
 
The correct statements are1. the oxygen atom has a greater attrac.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdfThe correct statements are1. the oxygen atom has a greater attrac.pdf
The correct statements are1. the oxygen atom has a greater attrac.pdf
 
This is a bit complex to answer as we have HCl and NaOH present, the.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdfThis is a bit complex to answer as we have HCl and NaOH present, the.pdf
This is a bit complex to answer as we have HCl and NaOH present, the.pdf
 
The possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdfThe possible causative agent is Corynebacterium diptheriaeSore thr.pdf
The possible causative agent is Corynebacterium diptheriaeSore thr.pdf
 
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdfThe answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
The answer is E) 1,2, and 3.The solubility of a gas in solvents de.pdf
 
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdfRainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
RainfallTest.java import java.util.Arrays; import java.util.Sc.pdf
 
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdfby taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
by taking p1,p2,p3 as points in cordinate system.. displavement can .pdf
 
import java.util.; public class DecimalToBinary { public stat.pdf
import java.util.; public class DecimalToBinary { public stat.pdfimport java.util.; public class DecimalToBinary { public stat.pdf
import java.util.; public class DecimalToBinary { public stat.pdf
 
i did not get itSolutioni did not get it.pdf
i did not get itSolutioni did not get it.pdfi did not get itSolutioni did not get it.pdf
i did not get itSolutioni did not get it.pdf
 
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdfHello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
Hello!!!!!!! This answer will help you ) H2Se would occur in a .pdf
 
Here is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdfHere is the code for youimport java.util.Scanner; import java.u.pdf
Here is the code for youimport java.util.Scanner; import java.u.pdf
 
Following are the changes mentioned in bold in order to obtain the r.pdf
Following are the changes mentioned in bold in order to obtain the r.pdfFollowing are the changes mentioned in bold in order to obtain the r.pdf
Following are the changes mentioned in bold in order to obtain the r.pdf
 
During meiosis, each member of a pair of genes tends to be randomly .pdf
During meiosis, each member of a pair of genes tends to be randomly .pdfDuring meiosis, each member of a pair of genes tends to be randomly .pdf
During meiosis, each member of a pair of genes tends to be randomly .pdf
 
B parents marital statusSolutionB parents marital status.pdf
B parents marital statusSolutionB parents marital status.pdfB parents marital statusSolutionB parents marital status.pdf
B parents marital statusSolutionB parents marital status.pdf
 
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdfANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
ANSWERS12. B collecting ducts13. B efferent arteriol15. juxtag.pdf
 
Array- Arrays is a collection of data items with same data type and.pdf
Array- Arrays is a collection of data items with same data type and.pdfArray- Arrays is a collection of data items with same data type and.pdf
Array- Arrays is a collection of data items with same data type and.pdf
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 

Recently uploaded (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 

We will be making 4 classes Main - for testing the code Hi.pdf

  • 1. /* We will be making 4 classes: Main - for testing the code HighscoreManager - to manage the high-scores HighscoreComparator - I will explain this when we get there Score - also this I will explain later all this classes will be in the package "highscores"/* //The Score Class package highscores; import java.io.Serializable; public class Score implements Serializable { private int score; private String naam; public int getScore() { return score; } public String getNaam() { return naam; } public Score(String naam, int score) { this.score = score; this.naam = naam; } }/*This class makes us able to make an object (an arraylist in our case) of the type Score that contains the name and score of a player. We implement serializable to be able to sort this type./* //The ScoreComparator Class package highscores; import java.util.Comparator; public class ScoreComparator implements Comparator { public int compare(Score score1, Score score2) { int sc1 = score1.getScore(); int sc2 = score2.getScore(); if (sc1 > sc2){ return -1;
  • 2. }else if (sc1 < sc2){ return +1; }else{ return 0; } } } /*This class is used to tell Java how it needs to compare 2 objects of the type score. -1 means the first score is greater than the 2nd one, +1 (or you can just put 1) means it's smaller and 0 means it's equal./* //The HighscoreManager Class /*First we will be making the HighscoreManager Class, this class will do the most important part of the high-score system. We will be using this as our base for the class:/* package highscores; import java.util.*; import java.io.*; public class HighscoreManager { // An arraylist of the type "score" we will use to work with the scores inside the class private ArrayList scores; // The name of the file where the highscores will be saved private static final String HIGHSCORE_FILE = "scores.dat"; //Initialising an in and outputStream for working with the file ObjectOutputStream outputStream = null; ObjectInputStream inputStream = null; public HighscoreManager() { //initialising the scores-arraylist scores = new ArrayList(); } } /*I have added comments to explain what's already in the class. We will be using a binary file to keep the high-scores in, this will avoid cheating. To work with the scores we will use an arraylist. An arraylist is one of the great things that java has and it's much better to use in this case than a regular array. Now we will add some methods and functions./*
  • 3. public ArrayList getScores() { loadScoreFile(); sort(); return scores; } /*This is a function that will return an arraylist with the scores in it. It contains calls to the function loadScoreFile() and sort(), these functions will make sure you have the scores from your high-score file in a sorted order. We will be writing these functions later on./* private void sort() { ScoreComparator comparator = new ScoreComparator(); Collections.sort(scores, comparator); } /*This function will create a new object "comparator" from the class ScoreComparator. the Collections.sort() function is in the Java Collections Class (a part of java.util). It allows you to sort the arraylist "scores" with help of "comparator"./* public void addScore(String name, int score) { loadScoreFile(); scores.add(new Score(name, score)); updateScoreFile(); } /*This method is to add scores to the scorefile. Parameters "name" and "score" are given, these are the name of the player and the score he had. First the scores that are allready in the high-score file are loaded into the "scores"-arraylist. Afther that the new scores are added to the arraylist and the high-score file is updated with it.*/ public void loadScoreFile() { try { inputStream = new ObjectInputStream(new FileInputStream(HIGHSCORE_FILE)); scores = (ArrayList) inputStream.readObject(); } catch (FileNotFoundException e) { System.out.println("[Laad] FNF Error: " + e.getMessage()); } catch (IOException e) { System.out.println("[Laad] IO Error: " + e.getMessage()); } catch (ClassNotFoundException e) { System.out.println("[Laad] CNF Error: " + e.getMessage()); } finally {
  • 4. try { if (outputStream != null) { outputStream.flush(); outputStream.close(); } } catch (IOException e) { System.out.println("[Laad] IO Error: " + e.getMessage()); } } } /*This function will load the arraylist that is in the high-score file and will put it in the "scores"-arraylist. The try-catch structure will avoid that your program crashes when there is something wrong while loading the file (like when the file is corrupted or doesn't exist)./* public void updateScoreFile() { try { outputStream = new ObjectOutputStream(new FileOutputStream(HIGHSCORE_FILE)); outputStream.writeObject(scores); } catch (FileNotFoundException e) { System.out.println("[Update] FNF Error: " + e.getMessage() + ",the program will try and make a new file"); } catch (IOException e) { System.out.println("[Update] IO Error: " + e.getMessage()); } finally { try { if (outputStream != null) { outputStream.flush(); outputStream.close(); } } catch (IOException e) { System.out.println("[Update] Error: " + e.getMessage()); } } } /*This is about the same as loadScoreFile(), but instead of reading the file it will be writing the "score"-arraylist to the file./*
  • 5. public String getHighscoreString() { String highscoreString = ""; Static int max = 10; ArrayList scores; scores = getScores(); int i = 0; int x = scores.size(); if (x > max) { x = max; } while (i < x) { highscoreString += (i + 1) + ".t" + scores.get(i).getNaam() + "tt" + scores.get(i).getScore() + " "; i++; } return highscoreString; } /*Depending on how you want to display your highscores this function can be either usefull or not usefull. But I have put it in here anyway. It can be used for both console and GUI (in GUI you can put the high-score string into a label). The function will only have the top 10 players but you can adjust the variable "max" to change that./* /*The Main Class This class is just to test out the code and it shows you how you can implement it into your own game./* package highscores; public class Main { public static void main(String[] args) { HighscoreManager hm = new HighscoreManager(); hm.addScore("Bart",240); hm.addScore("Marge",300); hm.addScore("Maggie",220); hm.addScore("Homer",100); hm.addScore("Lisa",270); System.out.print(hm.getHighscoreString());
  • 6. } } /*First you have to create an object from the HighscoreManager class, we will call it "hm" in here. Afther that you can add scores by using the .addScore() method. The first parameter has to be the name of your player and the 2nd one is the highscore (as an int). You can print the getHighscoreString function to get the highscore in String-format and display them on the console with System.out.print() Note: the first time you run you will get a "FNF Error", this means that the program hasn't found the highscore-file, this is logical because we haven't created that, but you don't have to worry, Java will create one itself, so afther the first time you won't have the error anymore. /* Solution /* We will be making 4 classes: Main - for testing the code HighscoreManager - to manage the high-scores HighscoreComparator - I will explain this when we get there Score - also this I will explain later all this classes will be in the package "highscores"/* //The Score Class package highscores; import java.io.Serializable; public class Score implements Serializable { private int score; private String naam; public int getScore() { return score; } public String getNaam() { return naam; } public Score(String naam, int score) { this.score = score; this.naam = naam;
  • 7. } }/*This class makes us able to make an object (an arraylist in our case) of the type Score that contains the name and score of a player. We implement serializable to be able to sort this type./* //The ScoreComparator Class package highscores; import java.util.Comparator; public class ScoreComparator implements Comparator { public int compare(Score score1, Score score2) { int sc1 = score1.getScore(); int sc2 = score2.getScore(); if (sc1 > sc2){ return -1; }else if (sc1 < sc2){ return +1; }else{ return 0; } } } /*This class is used to tell Java how it needs to compare 2 objects of the type score. -1 means the first score is greater than the 2nd one, +1 (or you can just put 1) means it's smaller and 0 means it's equal./* //The HighscoreManager Class /*First we will be making the HighscoreManager Class, this class will do the most important part of the high-score system. We will be using this as our base for the class:/* package highscores; import java.util.*; import java.io.*; public class HighscoreManager { // An arraylist of the type "score" we will use to work with the scores inside the class private ArrayList scores; // The name of the file where the highscores will be saved private static final String HIGHSCORE_FILE = "scores.dat";
  • 8. //Initialising an in and outputStream for working with the file ObjectOutputStream outputStream = null; ObjectInputStream inputStream = null; public HighscoreManager() { //initialising the scores-arraylist scores = new ArrayList(); } } /*I have added comments to explain what's already in the class. We will be using a binary file to keep the high-scores in, this will avoid cheating. To work with the scores we will use an arraylist. An arraylist is one of the great things that java has and it's much better to use in this case than a regular array. Now we will add some methods and functions./* public ArrayList getScores() { loadScoreFile(); sort(); return scores; } /*This is a function that will return an arraylist with the scores in it. It contains calls to the function loadScoreFile() and sort(), these functions will make sure you have the scores from your high-score file in a sorted order. We will be writing these functions later on./* private void sort() { ScoreComparator comparator = new ScoreComparator(); Collections.sort(scores, comparator); } /*This function will create a new object "comparator" from the class ScoreComparator. the Collections.sort() function is in the Java Collections Class (a part of java.util). It allows you to sort the arraylist "scores" with help of "comparator"./* public void addScore(String name, int score) { loadScoreFile(); scores.add(new Score(name, score)); updateScoreFile(); } /*This method is to add scores to the scorefile. Parameters "name" and "score" are given, these are the name of the player and the score he had.
  • 9. First the scores that are allready in the high-score file are loaded into the "scores"-arraylist. Afther that the new scores are added to the arraylist and the high-score file is updated with it.*/ public void loadScoreFile() { try { inputStream = new ObjectInputStream(new FileInputStream(HIGHSCORE_FILE)); scores = (ArrayList) inputStream.readObject(); } catch (FileNotFoundException e) { System.out.println("[Laad] FNF Error: " + e.getMessage()); } catch (IOException e) { System.out.println("[Laad] IO Error: " + e.getMessage()); } catch (ClassNotFoundException e) { System.out.println("[Laad] CNF Error: " + e.getMessage()); } finally { try { if (outputStream != null) { outputStream.flush(); outputStream.close(); } } catch (IOException e) { System.out.println("[Laad] IO Error: " + e.getMessage()); } } } /*This function will load the arraylist that is in the high-score file and will put it in the "scores"-arraylist. The try-catch structure will avoid that your program crashes when there is something wrong while loading the file (like when the file is corrupted or doesn't exist)./* public void updateScoreFile() { try { outputStream = new ObjectOutputStream(new FileOutputStream(HIGHSCORE_FILE)); outputStream.writeObject(scores); } catch (FileNotFoundException e) { System.out.println("[Update] FNF Error: " + e.getMessage() + ",the program will try and make a new file"); } catch (IOException e) { System.out.println("[Update] IO Error: " + e.getMessage());
  • 10. } finally { try { if (outputStream != null) { outputStream.flush(); outputStream.close(); } } catch (IOException e) { System.out.println("[Update] Error: " + e.getMessage()); } } } /*This is about the same as loadScoreFile(), but instead of reading the file it will be writing the "score"-arraylist to the file./* public String getHighscoreString() { String highscoreString = ""; Static int max = 10; ArrayList scores; scores = getScores(); int i = 0; int x = scores.size(); if (x > max) { x = max; } while (i < x) { highscoreString += (i + 1) + ".t" + scores.get(i).getNaam() + "tt" + scores.get(i).getScore() + " "; i++; } return highscoreString; } /*Depending on how you want to display your highscores this function can be either usefull or not usefull. But I have put it in here anyway. It can be used for both console and GUI (in GUI you can put the high-score string into a label). The function will only have the top 10 players but you can adjust the variable "max" to change that./*
  • 11. /*The Main Class This class is just to test out the code and it shows you how you can implement it into your own game./* package highscores; public class Main { public static void main(String[] args) { HighscoreManager hm = new HighscoreManager(); hm.addScore("Bart",240); hm.addScore("Marge",300); hm.addScore("Maggie",220); hm.addScore("Homer",100); hm.addScore("Lisa",270); System.out.print(hm.getHighscoreString()); } } /*First you have to create an object from the HighscoreManager class, we will call it "hm" in here. Afther that you can add scores by using the .addScore() method. The first parameter has to be the name of your player and the 2nd one is the highscore (as an int). You can print the getHighscoreString function to get the highscore in String-format and display them on the console with System.out.print() Note: the first time you run you will get a "FNF Error", this means that the program hasn't found the highscore-file, this is logical because we haven't created that, but you don't have to worry, Java will create one itself, so afther the first time you won't have the error anymore. /*