1
public void deposit(double depositAmount, String userName) throws IOException {
    //opens the file that stores the account balance
    File balanceLocation = new File(ACCOUNT_BALANCE_LOCATION+userName+".txt");
        
    //creates an object of the scanner class
    Scanner balanceReader = new Scanner(ACCOUNT_BALANCE_LOCATION+balanceLocation+".txt");

    //creates print writer object
    PrintWriter deposit = new PrintWriter (balanceLocation);
    
    double balance = balanceReader.nextDouble();
    double postDepositBalance = balance + depositAmount;
        
    deposit.println(postDepositBalance);
        
    deposit.close();
    balanceReader.close();      
}

Below code is in main I expected the program to work but every time I attempt to deposit any amount to the file it gives me an error:

String depositAmount = JOptionPane.showInputDialog("Enter Deposit Amount:");        

double convertedDeposit = Double.parseDouble(depositAmount);
                
JOptionPane.showMessageDialog(null, "New Balance: $"+ convertedDeposit);                
                
bank.deposit(convertedDeposit, username);   
                
JOptionPane.showMessageDialog(null, "New Balance: $"+ bank.balance(username));

I expected it to input the deposited amount to the file but instead got java.util.InputMismatchException

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Koka
  • 11
  • 2
  • 1
    Please read [mcve] and enhance your question accordingly. – GhostCat Feb 06 '19 at 02:10
  • 1
    Scanner throws InputMismatchException if the input field cannot be parsed to the datatype you're requesting - eg, if the next item being scanned was "xyz", then calling "nextDouble()" on it would throw that exception. So also enhance your question with the input data, and also your locale (eg see https://stackoverflow.com/questions/36912470/why-is-nextdouble-from-the-scanner-method-sending-me-exception ) – racraman Feb 06 '19 at 02:15
  • In addition to what @racraman says, you may be interested in `hasNextDouble()` in the same `Scanner` ... – ivanivan Feb 06 '19 at 02:41

1 Answers1

0

Like without checking a object is null, if you attempt to use it you got NullPointerException if it is null. Same logic is concerned in this situation too. You do not know that the next element is double or not and you are attempting to obtain double without knowing what type it is. So you should check it before use it like:

double balance = 0.0;
if( balanceReader.hasNextDouble())
    balance = balanceReader.nextDouble();
else
    // you may assign a value that informs you that next object is not double to error handling
Y.Kakdas
  • 833
  • 7
  • 17