【发布时间】:2021-10-31 05:27:27
【问题描述】:
我有一个文件读取器问题,如果找不到该值,我想返回 null。但该方法是一个 Float 方法。
public float getBalance(int accountNo) throws FileNotFoundException {
Scanner reader = new Scanner(new FileReader(bankfile));
String currentline = "";
try {
while((currentline = reader.nextLine())!= null) {
String line[] = currentline.split(",");
System.out.println(currentline);
System.out.println(line[0]);
if(Integer.parseInt(line[0]) == accountNo) {
this.accountBalance = Float.parseFloat(line[1]);
}
}
}
catch(NoSuchElementException e) {
System.out.println("The account number is not found");
// I want the method to end here if the account number is not found or just return null.
}
return this.accountBalance;
}
这是文件。
File:
2,2.0,Active
1,1.0,Active
3,3.0,Active
4,4.0,Active
5,5.0,Active
我想要这个代码
System.out.println(name.getbalance(6));
只返回打印行“未找到此帐号”而不返回 0.0
我做不到
if(balance == 0.0){
System.out.println("This account number is not found");
}
因为某些帐户可能有 0 余额。
【问题讨论】:
-
账户余额可以为负数吗?如果不是,则返回 -1。
-
使用optional types。这不仅仅是对
float的好建议。从各个方面来说,它都比null好。 -
返回
Optional,或者返回包装器Float,可以为null。 PS:金额绝不能浮动
标签: java exception filereader