我理解如何搜索txt文件以搜索值(或者在这种情况下为id),但通常会返回它找到的第一个选项。
我如何处理这个以便它找到文件中与id相关的最后一个值并使用它? (在这种情况下,卡ID为17的余额为813。
txt文件示例
17,721.0
17,744.0
17,767.0
17,790.0
17,813.0
我当前的搜索代码。
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;
}
答案 0 :(得分:1)
lastIndexOf(String)将为您提供最后一次出现的字符串。
如果没有,你会想要这样的东西:
String cardInfo;
String cardNumberString = cardNumber + ","; // makes sure that you don't get your
// id in the middle of a value
while((line = br.readLine()) != null) {
if(line.indexOf(cardNumberString) != -1)
cardInfo = line;
}