PDA

View Full Version : Need help with java program



LOST IN THE JAVA WORLD
11-19-2008, 03:14 PM
I have a program to make that involves me creating a text file that holds the top five scores from a guessing number game. i have to display the top five scores in order from greatest to least before the game starts. then the game starts and after the game ends the score from the user will be saved in the file and will go through the process of where it stands in the order of the scores.

when reading the input file in i have to display it through an array code also.

&& the output file for the top five scores has to write over the old score file instead of creating a new file.

omg i need help badly...please anybody

Twey
11-20-2008, 04:15 AM
import java.io.*;
import java.util.ArrayList;

public class ScoreFile extends File {
public ScoreFile(String path) {
super(path);
}

public Score[] readScores() {
BufferedInputReader in = new BufferedReader(new FileReader(this));
String ln;
ArrayList<Score> r;

while ((ln = in.readLine()) != null)
r.add(Score.fromLine(ln));

in.close();

return r.toArray();
}

public void writeScores(Score[] scores) {
BufferedWriter out = new BufferedWriter(new FileWriter(this));

for (Score score : scores) {
out.write(score.toLine());
out.newLine();
}

out.close();
}

public void printScores() {
Score[] scores = readScores();

for (Score score : scores)
System.out.writeln(score.prettyPrint());
}
}
public class Score {
public int score;
public Player player;

public Score(Player player, int score) {
this.player = player;
this.score = score;
}

public static Score fromLine(String line) {
String[] words;
StringBuilder name = new StringBuilder();
int i;

try {
words = line.split(" ");
} catch (PatternSyntaxException e) {}

for (i = 0; i < words.length - 1; ++i)
name.append(words[i] + (i == words.length - 2 ? "" : " "));

return new Score(name, Integer.parseInt(words[i]));
}

public String toLine() {
return this.name + " " + this.score;
}

public String prettyPrint() {
return this.name + ":\t" + this.score;
}
}Haskell equivalent:
type Player = String
data Score = Score Player Integer
deriving (Show, Read)

readScores :: FilePath -> IO [Score]
readScores p = readFile p >>= return . map read . lines

writeScores p = writeFile p . map show

printScores p = readFile p >>= mapM_ (putStrLn . formatScore) lines
where formatScore (Score p s) = p ++ ":\t" ++ show sBoth untested.