所以我有一个数独游戏,我正在尝试实现一个高分系统(记录前五名玩家)它基于球员的时间。时间越短,高分的等级越高。我曾想过如何通过流。但是,我不知道如何将高分添加到我的2D阵列(nametime[5][2]
)。我可以添加一个名字和分数,但是当我再次玩我的游戏时,我无法添加新的名字和分数。将新名称和分数添加到现有2D阵列+ I/O流?
变量:
private String[][] nametime = new String[5][2];
private String[] names = new String[5];
private String[] times = new String[5];
这是我到目前为止已经完成:
//assigns values to names[] and times[]
private void addNamesAndTimes(String name, String score){
names[0] = name;
times[0] = score;
System.out.println("Player: " + name + " || " + "Time: " + score);
}
我只分配的名称和得分,以他们的第一个指数,names[0]
和times[0]
,因为这是我的问题是。我不知道如何继续给我的数组添加名称和分数。
//merges names[] and times[] array into one 2D array nametime[][]
private String[][] mergeArrays(String[] a, String[] b){
for(int i = 0; i < nametime.length; i++){
nametime[i][0] = a[i];
nametime[i][1] = b[i];
}
return nametime;
}
我决定,因为我该怎么办与times[]
阵列后面的东西合并我names[]
和times[]
阵列。 (分数的比较)
public void createScoreFile(String name, String score){
addNamesAndTimes(name, score);
File file = new File("Scores.txt");
try {
if(!file.exists()){
System.out.println("Creating new file...");
file.createNewFile();
}
FileOutputStream fo = new FileOutputStream(file, true);
PrintStream ps = new PrintStream(fo);
for(int i = 0; i < nametime.length; i++){
for(int j = 0; j < nametime[0].length; j++){
ps.print(mergeArrays(names, times)[i][j] + "\t");
}
ps.println();
}
ps.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
此方法是用于创建我的存储我的nametime[][]
阵列的文件
//reads the contents of the text file and outputs it back to nametime[][]
public String[][] loadScoreFile(){
File file = new File("Scores.txt");
try {
Scanner scan = new Scanner(file);
for(int i = 0; i < nametime.length; i++){
for(int j = 0; j < nametime[i].length; j++){
nametime[i][j] = scan.next();
}
}
System.out.println("Nametime Array:");
for(int i = 0; i < nametime.length; i++){
for(int j = 0; j < nametime[i].length; j++){
System.out.print(nametime[i][j] + "\t");
}
System.out.println();
}
} catch(Exception ex) {
ex.printStackTrace();
}
return nametime;
}
此方法读我Score.txt文件
//method for showing the table and frame
public void showFrame(){
table = new JTable(loadScoreFile(), header);
*other GUI stuff here*
}
我将不胜感激任何人可以帮助我!
编辑:这里再次重申我的问题。当我完成游戏时,它应该在阵列和.txt文件中记录玩家名字和得分。然后我关闭比赛。当我打开游戏并再次完成游戏时,它将不得不将名称和分数再次存储到数组和.txt文件中。但就我而言,这并非如此。
感谢您的回答。我是否仍然使用流来实现这一点?因为我不能想到任何可以存储和记住我已经存在的价值的东西。 – alicedimarco 2012-04-05 10:25:24
您可以使用相同的流方式来保存和加载这些文件。 或者,您可以创建一个新的类,该类具有“结果”作为字段并将其声明为可序列化。这可能会更快,但该文件不会是人类可读的。您可以查看以下链接了解更多详情:http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serialTOC.html – MasterF 2012-04-05 11:25:20
我很感激。另一个问题是,TreeSet能够跟踪已经保存的内容吗?例如,我玩游戏并记录名称+分数。当我关闭游戏并再次打开游戏并进行游戏(需要另一个名称和分数)时,TreeSet仍然保留以前的名称+分数和当前名称+分数吗? – alicedimarco 2012-04-05 11:41:46