我不断收到java.util.InputMismatchException错误我该如何解决?

时间:2019-02-06 02:07:52

标签: java

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

下面的代码位于主要位置,我希望程序能够正常工作,但是每次尝试将任何金额存入文件时,都会给我一个错误:

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

double convertedDeposit = Double.parseDouble(depositAmount);

JOptionPane.showMessageDialog(null, "New Balance: $"+ convertedDeposit);                

bank.deposit(convertedDeposit, username);   

JOptionPane.showMessageDialog(null, "New Balance: $"+ bank.balance(username));

我希望它将存入金额输入到文件中,但是却出现了java.util.InputMismatchException

1 个答案:

答案 0 :(得分:0)

就像不检查对象为null一样,如果尝试使用它,则为NullPointerException。在这种情况下,同样的逻辑也受到关注。您不知道下一个元素是否为double,并且您尝试获取double却不知道它是什么类型。因此,您应在使用它之前先进行检查,例如:

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