Search⌘ K

Solution Review: Design an ATM

Explore how to design an ATM program by applying boolean expressions and if statements in Java. Learn to validate user password and cash withdrawal conditions effectively to ensure secure and accurate transactions.

Rubric criteria

Solution

Java
class ATMmachine
{
public static void main (String args[])
{
ATM obj = new ATM("0-2281291291-21", "29wjsw2", 249000);
// Withdrawing the money
System.out.println( obj.withdrawal("29wjsw2", "34000"));
}
}
class ATM // Header of the class
{
//Private fields
private String accNo;
private String accPassword;
private double balance;
// The parameterized constructor
public ATM(String AccNo, String Password, double Balance)
{
accNo = AccNo;
accPassword = Password;
balance = Balance;
}
// Write your function withdrawal here
public String withdrawal(String password, String cash)
{
if (accPassword.equals(password)) // First checking the passowrd
{
/* Step 1: If cash is null; no further checks and return error message
Step 2: If cash doesn't have all numbers; no further checks and return error message
Step 3: If cash is greater than balance; no further checks and return error message
Step 4: If cash is greater than 50,000; return error message
*/
if (cash != null && cash.matches("[-+]?\\d*\\.?\\d+") && Double.parseDouble(cash) <= this.balance && Double.parseDouble(cash) <= 50000)
{
balance -= Double.parseDouble(cash); // Deducting balance
return "Withdrawal is successful. Your current balance is $" + balance;
}
else // error message
{
return "Please enter the correct amount.";
}
}
else // If password wasn't correct
{
return "Wrong Password!";
}
}
}

Rubric-wise explanation

  • At line 12, we declare the header of the ATM class. The class is public.

Point 1:

  • Look at line 28. We declare the header of the withdrawal method of the ATM class: public String withdrawal(String password, String cash). It takes the password and cash as input and returns the message (String) when called on an ATM object.

Point 2:

  • Look at line 30. We add a condition next to an if keyword. If the password given by a user matches the password of the object, then we proceed. Otherwise, the control will shift directly to line 47, and the machine will print the message: Wrong Password!

Point 3, 4:

  • Considering that the password is correct, we move forward. Look at line 37. Notice that we have combined four boolean expressions with the && operator. All of them must ...