Here is just a couple of snippets of code. The program allows a negative deposit
ID: 3558113 • Letter: H
Question
Here is just a couple of snippets of code. The program allows a negative deposit. How would I fix this? If you need all of the code just comment with ur email and I can give you whole code. I just figured it was to lengthy to post it all here.
private static void depositMoney(ArrayList<BankAccount> list) {
int index= -1;
do{
int number = accountNumber();
index = accountNumberExist(list, number);
if (index == -1) {
System.out.println("The account number " + number + " is not found!");
} else {
System.out.print("Enter money to deposit: $");
BigDecimal money = ammount();
list.get(index).deposit(money);
System.out.println("Account Number: " + list.get(index).getAccountNumber());
System.out.println("Current Balance: $" + new DecimalFormat("0.00").format((list.get(index).getBalance())));
}
}while(index==-1);
}
public static BigDecimal ammount() {
BigDecimal money = BigDecimal.ZERO;
boolean exceptionFlag = true;
do {
exceptionFlag = true;
try {
String inputAmount = input.nextLine();
money = new BigDecimal(inputAmount);
int decimalIndex = inputAmount.indexOf('.');
String temp = inputAmount.substring(decimalIndex + 1);
if (decimalIndex != -1)
if (!(temp.length() == 2)) {
exceptionFlag = false;
System.out.print("Enter valid amount (2 didit after decimal): ");
}
} catch (Exception e) {
System.out.print("Enter valid amount: ");
exceptionFlag = false;
}
} while (exceptionFlag == false);
return money;
}
}
Explanation / Answer
change your amount method as follows
public static BigDecimal ammount() {
BigDecimal money = BigDecimal.ZERO;
boolean exceptionFlag = true;
do {
exceptionFlag = true;
try {
String inputAmount = input.nextLine();
if(inputAmount.indexOf('-') == 0)
{
exceptionFlag = false;
}
else
{
money = new BigDecimal(inputAmount);
int decimalIndex = inputAmount.indexOf('.');
String temp = inputAmount.substring(decimalIndex + 1);
if (decimalIndex != -1)
if (!(temp.length() == 2)) {
exceptionFlag = false;
System.out.print("Enter valid amount (2 digit after decimal): ");
}
}
}
catch (Exception e) {
System.out.print("Enter valid amount: ");
exceptionFlag = false;
}
} while (exceptionFlag == false);
return money;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.