【问题标题】:How to return null in a float method [duplicate]如何在浮点方法中返回 null [重复]
【发布时间】: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


【解决方案1】:

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

解决方案:将方法签名更改为等效的包装类。

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2017-02-23
    • 2021-05-04
    • 2021-11-18
    相关资源
    最近更新 更多