java - 比较文本文件中的整数和涉及字符串的程序
问题描述
我试图将我的应用程序中的分数与已经保存在单独的文本文件中的分数进行比较,但徒劳无功。当不涉及字符串时比较分数很容易,但是当我保存分数并为其分配名称时,程序无法工作,因为它无法解析字符串和整数。
示例文本文件:
Name, 8
Name, 1
Name, 4
我用来比较的代码:
int highScore = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader("txt.txt"));
String line = reader.readLine();
while (line != null)
{
try {
int score = Integer.parseInt(line.trim());
if (score > highScore)
{
highScore = score;
}
} catch (NumberFormatException e1) {
//ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
line = reader.readLine();
}
reader.close();
} catch (IOException ex) {
System.err.println("ERROR");
}
其余代码都很好,并且在游戏完成将其与文件中的分数进行比较时生成分数,它在读取字符串时只生成一个 0 值并且不起作用。我不确定如何使用扫描仪/分隔符。
编辑:我希望程序执行并显示获得该高分的用户的名称。所以期望的输出是;
The all time high score was 8 by Name1
目前它只说高分(根据 Michu93 的输入)。
解决方案
从字符串中删除数字并将其解析为 int:
int score = Integer.valueOf(line.replaceAll("[^\\d.]", ""));
@编辑
int highScore = 0;
String name = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("txt.txt"));
String line = reader.readLine();
while (line != null) {
try {
int score = Integer.parseInt(line.split(" ")[1]);
if (score > highScore) {
highScore = score;
name = line.split(" ")[0].replace(",", "");
}
} catch (NumberFormatException e1) {
//ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
line = reader.readLine();
}
System.out.println(String.format("The all time high score was %s by %s", highscore, name));
} catch (IOException ex) {
System.err.println("ERROR");
} finally {
reader.close(); // close stream always in finnaly block or use try with resources!!!
}