我编写了一个游戏,我已经制作了这样你可以保存你的分数,如果你有一个好成绩,你将在前10名。我的问题是当我用保存的名称检索数据时,我只想要显示一部分数据,在这种情况下是10个名字。
这是我的代码。
public static void Highscore(List<Highscore> data) {
String HighscoreList = "";
try {
//Textfilens name
String filname = "Highscore.txt";
Scanner inFil = new Scanner(new File(filname));
while(inFil.hasNext()) {
String name = inFil.next();
String percent = inFil.next();
HighscoreLista += name + "\n" + percent + "%" + "\n\n";
} inFil.close();
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(null,"File was not found!");
}
JOptionPane.showMessageDialog(null, HighscoreList);
}//Highscore ends
如何在最终消息中显示一定比例的玩家(Highscorelist)。
感谢您的帮助。
答案 0 :(得分:0)
在函数中创建一个计数器变量来跟踪while循环中的项目数,并检查计数器变量以及while条件
public static void Highscore(List<Highscore> data) {
String HighscoreList = "";
int counter =0;
try {
//Textfilens name
String filname = "Highscore.txt";
Scanner inFil = new Scanner(new File(filname));
while(inFil.hasNext() && counter<=10) {
counter++;
String name = inFil.next();
String percent = inFil.next();
HighscoreLista += name + "\n" + percent + "%" + "\n\n";
} inFil.close();
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(null,"File was not found!");
}
JOptionPane.showMessageDialog(null, HighscoreList);
}//Highscore ends