gpt4 book ai didi

Java - 读取文件时出现问题

转载 作者:行者123 更新时间:2023-11-30 04:47:44 25 4
gpt4 key购买 nike

我有这个功能:

public static int checkRank(String lineToCompare){
int rank = 0;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("ranks.txt");

// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

String strLine;
//Read File Line By Line
System.out.println("SPOT 0");
while ((strLine = br.readLine()) != null) {
//Compare the line with the line to compare (string)
System.out.println("SPOT 1");
if(strLine.trim().equals(lineToCompare)) {
//I found it! Read the next line...
final String lineAfter = br.readLine();
rank = Integer.parseInt(lineAfter);
System.out.println("SPOT 2");
}else{
rank = 0;
System.out.println("SPOT 3");
}
}

//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}

System.out.println("Username: " + lineToCompare + " | Rank: " + rank);
return rank;
}

我的ranks.txt文件如下:

test1
2
test2
1

控制台输出(“SPOT”仅用于调试):

[Commands] SPOT 0
[Commands] SPOT 1
[Commands] SPOT 2
[Commands] SPOT 1
[Commands] SPOT 3
[Commands] SPOT 1
[Commands] SPOT 3
[Commands] Username: test1 | Rank: 0

正如你所看到的,如果它工作正常,它会说 test1 的等级为 2。有人可以帮助我找出问题吗?

最佳答案

你应该添加一个休息点;在打印出“SPOT 2”的行之后添加语句以结束 while 循环。

如果没有中断,则在读取“test2”行时将排名设置为 0,然后在读取“1”行时再次将排名设置为 0(while 循环一直持续到文件末尾)。

关于Java - 读取文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10592734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com