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
就像没有检查对象为空,如果您尝试使用它,你有NullPointerException异常,如果它是空的。同样的逻辑来讲在这种情况下也。你不知道下一个元素是两倍或不和你正试图获得不知道它是什么类型的两倍。所以,你应该检查之前,它这样使用它:
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