0

I have a filereader problem where I want to return null if the value is not found. But the method is a Float method.

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;
    }

This is the file.

File:
2,2.0,Active
1,1.0,Active
3,3.0,Active
4,4.0,Active
5,5.0,Active

I want this code

System.out.println(name.getbalance(6));

to return just the print line "This account number is not found" and not return 0.0

I can't do

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

since some account might have 0 balance.

ronron681
  • 29
  • 4
  • Can account balance be negative? If not, return -1. – Arpit Shukla Oct 31 '21 at 05:34
  • Use [optional types](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html). That's not just good advice for `float`. It's better than `null` in every sense of the word. – Silvio Mayolo Oct 31 '21 at 05:35
  • Return `Optional`, or return wrapper `Float` which can be null. PS: Amount must never be float – sidgate Oct 31 '21 at 05:37
  • Refer to class [java.util.OptionalDouble](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/OptionalDouble.html) as well as this SO question: [Primitive "nulls" and Java 8](https://stackoverflow.com/questions/29553024/primitive-nulls-and-java-8) – Abra Oct 31 '21 at 06:09

1 Answers1

2

Root Cause : Your return type is primitive and primitives can not be assigned null values.

Solution : Change the method signature to the equivalent wrapper class.

FYR code:

Modify the following line

public float getBalance(int accountNo) throws FileNotFoundException {

to

public Float getBalance(int accountNo) throws FileNotFoundException {

After this you can add the return null statement in your catch block as follows:

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

Note : Kindly add a generic exception also in your catch block to make your code more resilient to the unexpected exceptional cases.

FYR

catch(Exception e) {
   // write some error message or something
}
Sharad Nanda
  • 406
  • 1
  • 15
  • 27