Reputation: 638
I have this function:
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;
}
My ranks.txt
file is as follows:
test1
2
test2
1
The console outputs (the "SPOT"s were just used for debugging):
[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
As you can see, if it were working correctly it would say test1 has a rank of 2. Can someone help me identify the problem?
Upvotes: 1
Views: 111
Reputation: 372
You should add a break; statement after the line where you print out "SPOT 2" to end the while loop.
Without the break you set the rank to 0 when you read the line "test2" and then again when you read the line "1" (the while loop continues until the end of file).
Upvotes: 1
Reputation: 425418
You are overwriting rank
with 0
in the last loop iteration.
Break out of the loop using break;
when you get a hit.
Upvotes: 1