Checking account - Problem with withdrawing with overdraft - java

I'm having trouble with a Java OOP exercise. The program uses two classes, the object class Account and the Main class to print whatever the user wants.
It's a standard checkings account with an overdraft limit, the issue I'm having is printing out the account balance if the user decides to withdraw more than the account balance, I can't seem to get the overdraft logic down, can anyone help me out?
Account classs
public boolean withdraw(double amount) {
balance = this.getBalance() + overDraftLimit;
if ((balance - amount) >= 0) {
this.setBalance(this.getBalance() - amount);
balance -= amount;
return true;
} else if ((balance - amount) <= 0) {
System.out.println("The amount you wish to withdraw is more than your balance -> Using overdraft to complete your transaction!");
this.setBalance((this.getBalance() - amount) + overDraftLimit);
return true;
}
return false;
} // ***** WITHDRAW *****
// ***** toString *****
#Override
public String toString() {
return "Account numer: " + accountNumber + "\nYour current balance is: $" + balance + "\nYour overdraft limit is: $" + overDraftLimit;
}
}
### Main class
Account ac1 = new Account();
ac1.setAccountNumber(1234);
ac1.setOverDraftLimit(50);
System.out.println(ac1);
System.out.println("\nSucessful deposit");
ac1.deposit(100);
System.out.println("Your current balance is: $" + ac1.getBalance());
makeWithdraw(ac1, 50);
makeWithdraw(ac1, 50);
makeWithdraw(ac1, 25);
}
public static void makeWithdraw (Account ac1, double amount) {
if (ac1.withdraw(amount)) {
System.out.println("Withdraw was sucessful! Your new balance is: $" + ac1.getBalance());
} else {
System.out.println("Insufficient funds! Cannot withdraw " + amount + "Your current balance is: $" + ac1.getBalance());
}
}
}
This is the output:

This will be the proper logic to handle the overdraft during withdrawl.
public boolean withdraw(double amount) {
if(balance < -overDraftLimit) {
return false;
}
if ((balance - amount) >= -overDraftLimit) {
this.setBalance(this.getBalance() - amount);
balance -= amount;
return true;
}
return false;
} // ***** WITHDRAW *****
[EDIT]
Here is an running example
public class Test{
public static class A {
private int balance = 20;
private int overDraftLimit = 50;
public boolean withdraw(double amount) {
if(balance < -overDraftLimit) {
return false;
}
if ((balance - amount) >= -overDraftLimit) {
balance -= amount;
return true;
}
return false;
}
public int getBalance() {
return balance;
}
}
public static void main(String []args){
A a = new A();
System.out.println(a.getBalance());
System.out.println(a.withdraw(30));
System.out.println(a.getBalance());
System.out.println(a.withdraw(40));
System.out.println(a.getBalance());
System.out.println(a.withdraw(1));
System.out.println(a.getBalance());
}
}
Output:
20
true
-10
true
-50
false
-50

Related

NoSuchElementException with java.util.scanner in school project

I am working on a school project. I have all the functionality working, I made it on Eclipse and it runs very well but when I submit the project through Mimir which is an online tool to grade your project, during deposits and withdraws it gives the following error:
Enter the amount you want to Deposit :$Exception in thread "main" java.util.NoSuchElementException
13 at java.util.Scanner.throwFor(Scanner.java:862)
14 at java.util.Scanner.next(Scanner.java:1485)
15 at java.util.Scanner.nextDouble(Scanner.java:2345)
16 at BankAccount.deposit(BankAccount.java:24)
17 at SavingsAccountDemo.main(SavingsAccountDemo.java:30)
The project does says the following: Please make sure that your classes throw appropriate exceptions when an attempt is made to insert invalid data.
I tried to add the try and catch with java.util.InputMismatchException e and java.util.NoSuchElementException but it doesn't seem to be fixing it. I think it's because the userInput is a double and they are entering something different. Any ideas how can I fix that? I am going crazy, been trying to fix it for hours. Here is the code:
///SavingsAccountDemo class
import java.util.*;
public class SavingsAccountDemo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double startingBalance;
double interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextDouble();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextDouble();
double bal = startingBalance;
double rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
BankDemo sv = new BankDemo(bal, rate);
while(startingBalance > -1) {
try {
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else if("e".equals(userInput)) {
ba.exit();
break;
}
else {
System.out.print("Error, option not valid\n");
}
}
catch (java.util.InputMismatchException e) {
System.out.print("Error");
}
}
}
}
///BankAccount class
import java.util.*;
public class BankAccount {
protected double balance;
protected double numDeposits;
protected double numWithdrawals;
protected double annualRate;
protected double monthlyServCharg;
protected boolean active;
Scanner keyboard = new Scanner(System.in);
public BankAccount(double startingBalance, double interestRate) {
balance = startingBalance;
annualRate = interestRate /= 100.0;
if(balance < 25) {
active = false;
} else
active = true;
}
public void deposit() {
try {
double valueD;
System.out.print("Enter the amount you want to Deposit :$");
valueD = keyboard.nextDouble();
if(valueD < 0) {
System.out.println("Error: Must enter positive value\n");
}
if( balance + valueD >= 25 && !active) {
System.out.print("Your account is now ACTIVE\n");
active = true;
}
balance += valueD;
numDeposits++;
}
catch (java.util.InputMismatchException e){
keyboard.nextLine();
}
}
public void withdraw() {
try {
double valueW;
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextDouble();
if(valueW < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numWithdrawals++;
if(balance < 0) {
System.out.print("ERROR: Transaction declined!! This transaction will cause overdraft or zero balance\n");
balance += valueW;
} else if(balance <= 25 && active) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
active = false;
}
if(numWithdrawals > 4) {
balance --;
System.out.print("You have exceeded monthly limit of withdrawals. Fee of $1 charged\n");
}
}
catch (java.util.InputMismatchException e) {
keyboard.nextLine();
}
}
public void totalBalance() {
System.out.printf("Your Balance is: %.2f\n", balance);
}
public void calcInterest() {
double monRate = annualRate / 12;
double monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f\n", balance);
}
public void exit() {
totalBalance();
System.out.print("Thank you. Bye");
}
}
When scanning an input with Scanner, the expected result is always a String.
Therefore, you have to check if the field is a double before assuming it is. You can use a cast and check with a try catch if casting raises an NumberFormatException error. If it is the case, the input is not valid. Otherwise, you can use that newly casted double in your program.

Handle Scanner exception on Java program

I am working on a school project. I have all the functionality working but when I submit the project through Mimir, during deposits and withdraws it gives the following error:
Enter the amount you want to Deposit :$Exception in thread "main" java.util.NoSuchElementException
13 at java.util.Scanner.throwFor(Scanner.java:862)
14 at java.util.Scanner.next(Scanner.java:1485)
15 at java.util.Scanner.nextDouble(Scanner.java:2345)
16 at BankAccount.deposit(BankAccount.java:24)
17 at SavingsAccountDemo.main(SavingsAccountDemo.java:30)
The project does says the following: Please make sure that your classes throw appropriate exceptions when an attempt is made to insert invalid data.
I tried to add the try and catch with java.util.InputMismatchException e but it doesn't seem to be fixing it. I think it's because the userInput is a double and they are entering something different. Any ideas how can I fix that? Here is the code:
///SavingsAccountDemo class
import java.util.*;
public class SavingsAccountDemo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double startingBalance;
double interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextDouble();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextDouble();
double bal = startingBalance;
double rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
BankDemo sv = new BankDemo(bal, rate);
while(startingBalance > -1) {
try {
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else if("e".equals(userInput)) {
ba.exit();
break;
}
else {
System.out.print("Error, option not valid\n");
}
}
catch (java.util.InputMismatchException e) {
System.out.print("Error");
}
}
}
}
///BankAccount class
import java.util.*;
public class BankAccount {
protected double balance;
protected double numDeposits;
protected double numWithdrawals;
protected double annualRate;
protected double monthlyServCharg;
protected boolean active;
Scanner keyboard = new Scanner(System.in);
public BankAccount(double startingBalance, double interestRate) {
balance = startingBalance;
annualRate = interestRate /= 100.0;
if(balance < 25) {
active = false;
} else
active = true;
}
public void deposit() {
try {
double valueD;
System.out.print("Enter the amount you want to Deposit :$");
valueD = keyboard.nextDouble();
if(valueD < 0) {
System.out.println("Error: Must enter positive value\n");
}
if( balance + valueD >= 25 && !active) {
System.out.print("Your account is now ACTIVE\n");
active = true;
}
balance += valueD;
numDeposits++;
}
catch (java.util.InputMismatchException e){
keyboard.nextLine();
}
}
public void withdraw() {
try {
double valueW;
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextDouble();
if(valueW < 0) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numWithdrawals++;
if(balance < 0) {
System.out.print("ERROR: Transaction declined!! This transaction will cause overdraft or zero balance\n");
balance += valueW;
} else if(balance <= 25 && active) {
System.out.print("Your balance is less than minimum balance. Your account is now INACTIVE\n");
active = false;
}
if(numWithdrawals > 4) {
balance --;
System.out.print("You have exceeded monthly limit of withdrawals. Fee of $1 charged\n");
}
}
catch (java.util.InputMismatchException e) {
keyboard.nextLine();
}
}
public void totalBalance() {
System.out.printf("Your Balance is: %.2f\n", balance);
}
public void calcInterest() {
double monRate = annualRate / 12;
double monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f\n", balance);
}
public void exit() {
totalBalance();
System.out.print("Thank you. Bye");
}
}

How can I allow the user to be able to input something by typing in the keyboard infinitely using the Scanner feature?

In my code, I was able to use the scanner feature to prompt the user to type a piece of text, however, I was only able to make it so the user can type once. To type again I would have to close the terminal, and open it again, how can I make it so that I can just type infinitely so that I wouldn't have to close it and reopen it every time in order to type again?
For context, this is my code, it is about a ticket machine which displays certain data, like the name of the person, the price, the total balance, etc. Currently I am doing the places. This means that I want the user to type any city in England, and a price would appear. But as I said, the user can only jarringly type one thing at a time, when they should be able to type without any limit.
import java.util.Scanner;
import java.lang.String;
public class TicketMachine
{
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost)
{
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice()
{
return price;
}
/**
* Return The amount of money already inserted for the
* next ticket.
*/
public int getBalance()
{
return balance;
}
/**
* Receive an amount of money from a customer.
* Check that the amount is sensible.
*/
public void insertMoney(int amount)
{
if(amount > 0) {
balance = balance + amount;
}
else {
System.out.println("Use a positive amount rather than: " +
amount);
}
}
/**
* Print a ticket if enough money has been inserted, and
* reduce the current balance by the ticket price. Print
* an error message if more money is required.
*/
public void printTicket()
{
if(balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
}
else {
System.out.println("You must insert at least: " +
(price - balance) + " more cents.");
}
}
/**
* Return the money in the balance.
* The balance is cleared.
*/
public int refundBalance()
{
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String [] args)
{
Scanner myScanner = new Scanner(System.in);
String answer = myScanner.nextLine();
if( answer.equals("London") )
{
System.out.println("£15");
}
if( answer.equals("Manchester") )
{
System.out.println("£20");
}
if( answer.equals("Brighton") )
{
System.out.println("£25");
}
if( answer.equals("Cornwall") )
{
System.out.println("£30");
}
if( answer.equals("Crystal Palace") )
{
System.out.println("£35");
}
if( answer.equals("Chealsea") )
{
System.out.println("£40");
}
if( answer.equals("Birmingham") )
{
System.out.println("£45");
}
if( answer.equals("Liverpool") )
{
System.out.println("£50");
}
if( answer.equals("Bristol") )
{
System.out.println("£55");
}
if( answer.equals("Leister") )
{
System.out.println("£60");
}
if( answer.equals("Newcastle") )
{
System.out.println("£65");
}
if( answer.equals("Cambridge") )
{
System.out.println("£70");
}
if( answer.equals("Bradford") )
{
System.out.println("£75");
}
if( answer.equals("Leeds") )
{
System.out.println("£80");
}
if( answer.equals("Oxford") )
{
System.out.println("£85");
}
if( answer.equals("Nottingham") )
{
System.out.println("£90");
}
if( answer.equals("Peterborough") )
{
System.out.println("£95");
}
if( answer.equals("Sheffield") )
{
System.out.println("£100");
}
}
}
Using a while true or a infinite loop isn't a good practice. You can use a do-while and check a flag (e.g. "exit") to close the program e.g.
import java.util.Scanner;
import java.lang.String;
public class TicketMachine {
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost) {
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice() {
return price;
}
/**
* Return The amount of money already inserted for the next ticket.
*/
public int getBalance() {
return balance;
}
/**
* Receive an amount of money from a customer. Check that the amount is sensible.
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Use a positive amount rather than: "
+ amount);
}
}
/**
* Print a ticket if enough money has been inserted, and reduce the current balance by the
* ticket price. Print an error message if more money is required.
*/
public void printTicket() {
if (balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Return the money in the balance. The balance is cleared.
*/
public int refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Enter your city, please:");
answer = myScanner.nextLine();
if (answer.equals("London")) {
System.out.println("£15");
}
else if (answer.equals("Manchester")) {
System.out.println("£20");
}
else if (answer.equals("Brighton")) {
System.out.println("£25");
}
else if (answer.equals("Cornwall")) {
System.out.println("£30");
}
else if (answer.equals("Crystal Palace")) {
System.out.println("£35");
}
else if (answer.equals("Chealsea")) {
System.out.println("£40");
}
else if (answer.equals("Birmingham")) {
System.out.println("£45");
}
else if (answer.equals("Liverpool")) {
System.out.println("£50");
}
else if (answer.equals("Bristol")) {
System.out.println("£55");
}
else if (answer.equals("Leister")) {
System.out.println("£60");
}
else if (answer.equals("Newcastle")) {
System.out.println("£65");
}
else if (answer.equals("Cambridge")) {
System.out.println("£70");
}
else if (answer.equals("Bradford")) {
System.out.println("£75");
}
else if (answer.equals("Leeds")) {
System.out.println("£80");
}
else if (answer.equals("Oxford")) {
System.out.println("£85");
}
else if (answer.equals("Nottingham")) {
System.out.println("£90");
}
else if (answer.equals("Peterborough")) {
System.out.println("£95");
}
else if (answer.equals("Sheffield")) {
System.out.println("£100");
}else {
System.out.println("ERROR: INVALID INPUT");
}
} while (answer != "exit");
}
}
PS use a switch case instead of if(){} e.g
import java.util.Scanner;
import java.lang.String;
public class TicketMachine {
private int price;
private int balance;
private int total;
/**
* Create a machine that issues tickets of the given price.
*/
public TicketMachine(int cost) {
price = cost;
balance = 0;
total = 0;
}
/**
* #Return The price of a ticket.
*/
public int getPrice() {
return price;
}
/**
* Return The amount of money already inserted for the next ticket.
*/
public int getBalance() {
return balance;
}
/**
* Receive an amount of money from a customer. Check that the amount is sensible.
*/
public void insertMoney(int amount) {
if (amount > 0) {
balance = balance + amount;
} else {
System.out.println("Use a positive amount rather than: "
+ amount);
}
}
/**
* Print a ticket if enough money has been inserted, and reduce the current balance by the
* ticket price. Print an error message if more money is required.
*/
public void printTicket() {
if (balance >= price) {
// Simulate the printing of a ticket.
System.out.println("HERE IS YOUR TICKET");
System.out.println("# Ticket");
System.out.println("# " + price + " cents.");
System.out.println("You have" + balance + "left");
// Update the total collected with the price.
total = total + price;
// Reduce the balance by the price.
balance = balance - price;
} else {
System.out.println("You must insert at least: "
+ (price - balance) + " more cents.");
}
}
/**
* Return the money in the balance. The balance is cleared.
*/
public int refundBalance() {
int amountToRefund;
amountToRefund = balance;
balance = 0;
return amountToRefund;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
String answer = "";
do {
System.out.println("Enter your city, please:");
answer = myScanner.nextLine();
switch (answer) {
case "London":
System.out.println("£15");
break;
case "Manchester":
System.out.println("£20");
break;
case "Brighton":
System.out.println("£25");
break;
case "Cornwall":
System.out.println("£30");
break;
case "Crystal Palace":
System.out.println("£35");
break;
case "Chealsea":
System.out.println("£40");
break;
case "Birmingham":
System.out.println("£45");
break;
case "Liverpool":
System.out.println("£50");
break;
case "Bristol":
System.out.println("£55");
break;
case "Leister":
System.out.println("£20");
break;
case "Newcastle":
System.out.println("£65");
break;
case "Cambridge":
System.out.println("£70");
break;
case "Bradford":
System.out.println("£75");
break;
case "Leeds":
System.out.println("£80");
break;
case "Oxford":
System.out.println("£85");
break;
case "Nottingham":
System.out.println("£90");
break;
case "Peterborough":
System.out.println("£95");
break;
case "Sheffield":
System.out.println("£100");
break;
default:
System.out.println("ERROR: INVALID INPUT");
break;
}
} while (answer != "exit");
}
}

Not getting the right output

Probably just a small error, but I cant seem to find it anywhere. When I run the program, it prints "After depositing $100: Savings Account:, also my withdraw class seems not to be working, as the balance after withdrawing money does not change.
public class CheckingandSavings
{
public static void main(String[] args) {
Savings savings = new Savings(1001,1000.0);
Checking checking = new Checking(1002, 2000.0);
System.out.println("At the beginning: " + savings);
savings.deposit(100);
System.out.println("After depositing $100: " + savings);
savings.withdraw(500);
System.out.println("After withdrawing $500: " + savings);
System.out.println("");
System.out.println("At the beginning: " + checking);
checking.deposit(100);
System.out.println("After depositing $100: " + checking);
checking.withdraw(500);
System.out.println("After withdrawing $500: " + checking);
}
}
public class Account {
private int accountNumber;
private double accountBalance;
//The Two-Arg Constructor
public Account(int accountNumber, double accountBalance)
{
setAccountBalance(accountBalance);
setAccountNumber(accountNumber);
}
//Getter for accountNumber
public int getAccountNumber()
{
return accountNumber;
}
//Setter for accountNumber
public void setAccountNumber(int accountNumber)
{
if (accountNumber >= 0)
this.accountNumber = accountNumber;
}
//Getter for accountBalance
public double getAccountBalance()
{
return accountBalance;
}
//Setter for accountBalance
public void setAccountBalance(double accountBalance)
{
if (accountNumber >= 0)
this.accountBalance = accountBalance;
}
//Deposit to accountBalance
public void deposit(double amount)
{
if (amount > 0)
this.accountBalance += amount;
}
//Withdraw from accountBalance
public double withdraw(double amount)
{
if (amount > 0 || amount > this.accountBalance)
return 0;
this.accountBalance -= amount;
return this.;
}
//Returns a string of the instance data
public String toString()
{
String result = "";
result += "Account Number: " + this.accountNumber;
result += "\nAccount Balance: $" + String.format("%.2f", this.accountBalance);
return result;
}
}
public class Savings extends Account {
//The two-arg constructor
public Savings(int accountNumber, double accountBalance)
{
super(accountNumber, accountBalance);
}
//Returns a string of the instance data
public String toString()
{
String result = "";
result += "Savings Account: \n" + super.toString();
return result;
}
}
public class Checking extends Account {
//The two-arg constructor
public Checking(int accountNumber, double accountBalance)
{
super(accountNumber,accountBalance);
}
//Returns a string of the instance data
public String toString() {
String result = "";
result += "Checking Account: \n" + super.toString();
return result;
}
}
Taking a look at your withdraw method:
//Withdraw from accountBalance
public double withdraw(double amount)
{
if (amount > 0 || amount > this.accountBalance) //This needs to be &&
return 0;
this.accountBalance -= amount;
return this.; //I am assuming you meant this to be this.accountBalance?
}
You are saying if the amount you want to withdraw is greater than 0 OR it is greater than your account balance, return 0. I think you want to say AND so instead put amount > 0 && amount > this.accountBalance
Also, you should be returning this.accountBalance.
Lastly, you should really put the #Override annotation above your toString methods. This lets the compiler know you are overriding a parents method.

Prevent an Added Variable from Exceeding Specified Number

I'm trying to make it so my methods payGourmet and payEconomical balance don't change if there's not enough money and don't drop below zero. Also so that my loadMoney method does not exceed 150 but still adds the specified number from the main. What am I doing wrong?
Import java.util.Scanner;
public class LyyraCard {
private double balance;
public LyyraCard(double balanceAtStart) {
this.balance = balanceAtStart;
}
public String toString() {
return "The card has " + this.balance + " euros";
}
public void payEconomical() {
if (this.balance > 0) {
this.balance -= 2.5;
}
}
public void payGourmet() {
if (this.balance > 0) {
this.balance -= 4.0;
}
}
public void loadMoney(double amount) {
if (this.balance < 150) {
this.balance += amount;
}
}
}
public class Main {
public static void main(String[] args) {
// add here code that tests LyraCard. However before doing 77.6 remove the
// other code
LyyraCard card = new LyyraCard(10);
System.out.println(card);
card.payEconomical();
System.out.println(card);
card.payGourmet();
System.out.println(card);
card.payGourmet();
System.out.println(card);
card.loadMoney(10);
System.out.println(card);
card.loadMoney(200);
System.out.println(card);
}
}
When you check if the balance is greater than 0 and then subtract an amount you could end up in a negative balance:
public void payEconomical() {
if (this.balance > 0) {
this.balance -= 2.5;
}
}
If balance = 1 this would yield a negative balance (-1.5).
You need to check if the balance is equal or greater than the amount you are to subtract
public void payEconomical() {
if (this.balance >= 2.5) {
this.balance -= 2.5;
}
else {
// There isn't enough money
}
}
Likewise for payGourmet:
if (this.balance >= 4.0) {
...
And in loadMoney you need to check if the current balance plus the added money is equal or less than 150:
if (this.balance + amount <= 150.0) {
this.balance += amount;
}
else {
// Amount too large.
}
To limit values to minimum or maximum values, use Math.min() or Math.max().
int valueA = -50;
valueA = Math.max(valueA, 0); //valueA is now 0;
int valueB = 200;
valueB = Math.min(valueB, 150); //valueB is now 150;
If you want to limit it to upper and lower bounds, just use both methods
int valueC = -50;
valueC = Math.min(Math.max(valueC, 0), 150); //valueC is now 0
int valueD = 200;
valueD = Math.min(Math.max(valueC, 0), 150); //valueD is now 150
edit: so for your example, use
public void loadMoney(double amount) {
this.balance = Math.min(this.balance + amount, 150);
}

Categories

Resources