如何在 float 方法中 return null

How to return null in a float method

我有一个文件读取器问题,如果找不到该值,我想 return 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));

到 return 只是打印行“找不到此帐号”而不是 return 0.0

我做不到

if(balance == 0.0){
System.out.println("This account number is not found");
}

因为某些账户可能有 0 余额。

根本原因:您的 return 类型是原始类型,不能为原始类型分配空值。

解决方案 : 将方法签名更改为等效的包装器 class.

FYR 代码:

修改以下行

public float getBalance(int accountNo) throws FileNotFoundException {

public Float getBalance(int accountNo) throws FileNotFoundException {

在此之后,您可以在 catch 块中添加 return null 语句,如下所示:

catch(NoSuchElementException e) {
     System.out.println("The account number is not found");
     return null;
}

注意:请在您的 catch 块中也添加一个通用异常,以使您的代码对意外异常情况更具弹性。

财政年度

catch(Exception e) {
   // write some error message or something
}