I understand how to search through a txt file searching for a value (or an id in this case) however usually this returns the first option it finds.
How would I work this so that it finds the last value in the file related to the id and uses that one? (in this case, the card ID of 17 has a balance of 813.
txt file example
17,721.0
17,744.0
17,767.0
17,790.0
17,813.0
my current search code.
public static double readBalance(int cardNumber)
{
double balance;
String line;
try {
File CbFile = new File("cardBalance.txt");
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(CbFile)));
while((line = br.readLine()) != null) {
if(line.indexOf(cardNumber) != -1)
break;
}
String[] s = line.split("\\,");
balance = Double.parseDouble(s[1]);
System.out.println("Blalance of " + cardNumber +
" is: " + s[1]);
br.close();
} catch(IOException e) {
System.out.println("read error: " + e.getMessage());
}
return balance;
}
lastIndexOf(String) will give you the last occurrence of a String, if you can read the entire file into memory at once.
If not, you’ll want something like: