I'm currently solving the PaymentCard exercise in https://java-programming.mooc.fi/part-4/1-introduction-to-object-oriented-programming and the output of this program should not be a negative balance. If ever the balance gets negative, it will not be printed. I added a conditional statement in both methods but my output keeps printing a negative balance.
Any help would genuinely be appreciated. Thanks!
//Desired Output:The card has a balance 5.0 euros
// The card has a balance 0.40000000000000036 euros
// The card has a balance 0.40000000000000036 euros
//My Output: The card has a balance of 5.0 euros
// The card has a balance of 0.40000000000000036 euros
// The card has a balance of -4.199999999999999 euros
public class MainProgram {
public static void main(String[] args) {
PaymentCard card = new PaymentCard(5);
System.out.println(card);
card.eatHeartily();
System.out.println(card);
card.eatHeartily();
System.out.println(card);
}
}
public class PaymentCard {
private double balance;
public PaymentCard(double openingBalance) {
this.balance = openingBalance;
}
public String toString() {
return "The card has a balance of " + this.balance + " euros";
}
public void eatAffordably() {
if (this.balance > 0) {
this.balance = this.balance - 2.60;
}
}
public void eatHeartily() {
if (this.balance > 0) {
this.balance = this.balance - 4.60;
}
}
}
Obviously you can print only amount greater then zero, but
I think a more correct and elegant solution is take into consideration also the amount you subtract:
public void eatAffordably() {
if (this.balance >= 2.60) {
this.balance = this.balance - 2.60;
}
}
public void eatHeartily() {
if (this.balance >= 4.60) {
this.balance = this.balance - 4.60;
}
}
Rather than having a toString method
public String toString() {
return "The card has a balance of " + this.balance + " euros";
}
and calling System.out.println(card);
create a method that does the actual printing e.g.
void printCard () {
if (this.balance > 0) {
System.out.println(card);
}
}
Related
I was working on an exercise in a Java programming book for beginners where I had to create a bank account with a withdraw limit of up to -1000 Euros. Somehow, even though the amount is -1000 Euros, the code executes the else code, which for me makes little sense. It shouldn't output the error in my opinion, but it does.
Here is the account code:
public class Account {
private String accountnumber;
protected double accountbalance;
Account(String an, double ab) {
accountnumber = an;
accountbalance = ab;
}
double getAccountbalance() {
return accountbalance;
}
String getAccountnumber() {
return accountnumber;
}
void deposit(double ammount) {
accountbalance += ammount;
}
void withdraw(double ammount) {
accountbalance -= ammount;
}
}
The extended account:
public class GiroAccount extends Account{
double limit;
GiroAccount(String an, double as, double l) {
super(an, as);
limit = l;
}
double getLimit() {
return limit;
}
void setLimit(double l) {
limit = l;
}
void withdraw(double ammount) {
if ((getAccountbalance() - ammount) >= limit) {
super.withdraw(ammount);
} else {
System.out.println("Error - Account limit is exceded!");
}
}
}
The code to test the accounts:
public class GiroAccountTest {
public static void main(String[] args) {
GiroAccount ga = new GiroAccount("0000000001", 10000.0, -1000.0);
ga.withdraw(11000.0);
System.out.println("Balance: " + ga.getAccountbalance());
ga.deposit(11000.0);
ga.withdraw(11001.0);
System.out.println("Balance: " + ga.getAccountbalance());
}
}
The output:
Balance: -1000.0
Error - Account limit is exceded!
Balance: 10000.0
Let's take step by step.
1. Start with 10000.0;
2. withdraw(11000.0) -> -1000.0
3. Print balance -> "Balance: -1000.0"
4. deposit(11000.0) -> 10000.0
5. withdraw(11001.0); -> -1001.0 < -1000.0
6. Overdrawn (enters else block) -> "Error - Account limit is exceeded"
7. Print balance -> "Balance: 10000.0"
If I'm wrong please correct me.
I would like someones expert opinion on both of my account class and the test account interest class. The issue I am facing is that the code from the test account interest class just multiplies on from the previous 12 month compute interest when it is supposed to be used only once.
The issue is in the
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
It is in this method of where the problem is that I should not use the balance but to use a variable that will store the answer but I did not understand the person that very clearly and he was very vague by only stating a variable should be used.
public class Account
{
private double balance; //STATE
private double interestRate; //STATE
private double rate;//STATE
public Account()
{
balance = 0;
interestRate = 0;
}
public Account(double amount, double interestRate)
{
balance = amount;
rate = interestRate;
}
public void deposit(double amount)
{
balance=balance+amount;
}
public void withdraw(double amount)
{
balance = balance - amount;
}
public void setInterest(double rate)
{
balance = balance + balance * rate;
//this.setInterst = setInterest;
//setInterest = InterestRate / 12;
}
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
public double getsetInterest()
{
return rate;
}
public double getBalance()
{
return balance;
}
public void close()
{
balance =0;
}
}
This is my test account interest class:
public class TestAccountInterest
{
public static void main (String[] args)
{
Account acc1 = new Account(100, 0.1);//0.10);
Account acc2 = new Account(133, 0.2); //0.20);
/*************************************
ACC1 ACCOUNT BELOW
*************************************/
//acc1.deposit(100);
//acc1.withdraw(100);
System.out.println(acc1.computeInterest(12));
// //acc1.computeInterest(12);
// System.out.println(acc1.computeInterest(24));
/**************************************
ACC2 ACCOUNT BELOW
**************************************/
acc2.withdraw(100);
acc2.deposit(100);
//acc2.computeInterest(24);
System.out.println(acc2.computeInterest(24));
}
}
This is the final output:
110.00000000000001
191.51999999999998
As you can see for the second one the figure is multiplied by the 12 month compute interest with the 24 month compute interest this stems from the method in the account class:
public double computeInterest(int n)
{
balance=balance*(Math.pow((1+rate),n/12));
return balance;
}
If I take out the balance it still causes and error so I confused on this particular part.
Code,
public double computeInterest(int n) {
balance = balance * (Math.pow((1 + rate), n / 12));
return balance;
}
should be changed to
public double computeInterest(int n) {
return balance * Math.pow(1 + rate, n / 12);
}
You shouldn't change balance field while computing interest. You might like to have a separate method to update balance where you do , balance = balance + computed_interest or something like that.
Also, I have remove unnecessary parenthesis. That was not an error but simply making your code less readable.
Ok I am having problems creating a transfer to method to transfer "money" from one account to the next. After the transfer the amounts of each account would be printed out. I created the code but when I run it the amount transferred is set to the bank account amount. It should just deduct from one account and add to the next account. What am I doing wrong?
This is my class with contructors and methods:
public class Account {
// Instance variables
private double balance;
// Constructors
public Account(double initialBalance) {
balance = initialBalance;
}
public Account(int account, double balance) {
this.balance = balance;
}
public Account() {
balance = 0.0;
}
// Instance methods
public void setBalance() {
balance = Math.random() * 1000;
balance = Math.round((balance * 100.0)+.5) / 100.0;
}
public void deposit(double amount) {
balance = balance + amount;
}
public void withdraw(double amount) {
balance = balance - amount;
}
public double getBalance() {
balance = Math.round((balance * 100.0)+.5) / 100.0;
return balance;
}
public void close() {
balance = 0.0;
}
public void transferTo(Account bank, double x) {
if (x <= balance) {
withdraw(x);
bank.deposit(x);
System.out.println("\nTransfer succesful. Tansfered: $" + bank.getBalance());
} else if (x > balance) {
System.out.println("\nTransfer failed, not enough balance!");
}
}
}
This is my class with the main method
public class MyBank {
public static void main(String[] args) {
Account[] bank = { new Account(), new Account(), new Account(),
new Account() };
bank[0].setBalance();
bank[1].setBalance();
bank[2].setBalance();
bank[3].setBalance();
System.out.println("Accounts 1 balance is: $" + bank[0].getBalance());
System.out.println("Accounts 2 balance is: $" + bank[1].getBalance());
System.out.println("Accounts 3 balance is: $" + bank[2].getBalance());
System.out.println("Accounts 4 balance is: $" + bank[3].getBalance());
double x = Math.random()*100;
bank[0].transferTo(bank[1], x);
System.out.println("Remaining balance of Account 1: $" + bank[0].getBalance());
System.out.println("Remaining balance of Account 2: $" + bank[1].getBalance());
double y = (Math.random()*300);
bank[2].transferTo(bank[3], y);
System.out.println("Remaining balance of Account 3: $" + bank[2].getBalance());
System.out.println("Remaining balance of Account 4: $" + bank[3].getBalance());
}
}
One issue you did have, is that you were accidentally printing the BALANCE rather than the amount actually transferred, in your transferTo() method. I fixed this. On another note, if you're going to be printing these numbers out, look into printf() to make them appear as actual dollar amounts. I did it to one of the lines to show you an example.
PS - Try NOT using Math.random() for stuff when you're trying to debug.
public void transferTo(Account bank, double x) {
if (x <= this.balance) {
withdraw(x);
bank.deposit(x);
System.out.println("\nTransfer succesful. Tansfered: $" + x);
} else { //does not need to be else if, because if not <=, it MUST be >.
System.out.println("\nTransfer failed, not enough balance!");
}
}
I can verify that the method works perfectly fine, after these edits, on my machine. This is what I used to test:
public class MyBank {
public static void main(String[] args) {
Account[] bank = { new Account(), new Account(), new Account(),
new Account() };
bank[0].setBalance();
bank[1].setBalance();
bank[2].setBalance();
bank[3].setBalance();
double x = 100.00;
System.out.printf("Transferring $%.2f from Acc 1 to Acc 2.\n", x); //printf example
System.out.println("Acc 1 previous balance: " + bank[0].getBalance());
System.out.println("Acc 2 previous balance: " + bank[1].getBalance());
bank[0].transferTo(bank[1], x);
System.out.println("Acc 1 new balance: " + bank[0].getBalance());
System.out.println("Acc 2 new balance: " + bank[1].getBalance());
}
}
And lastly, my output:
Transferring $100.00 from Acc 1 to Acc 2.
Acc 1 previous balance: 106.76
Acc 2 previous balance: 266.18
Transfer succesful. Transfered: $100.0
Acc 1 new balance: 6.77
Acc 2 new balance: 366.19
System.out.println("\nTransfer succesful. Tansfered: $" + bank.getBalance());
This prints the other account's new balance, because that's what you told it to do.
If you want to print the amount transferred:
System.out.println("\nTransfer succesful. Tansfered: $" + x);
// Bank account class
class BankAccount {
constructor(fname, lname, account_number) {
const minBalance = 10000;
this.name = `${fname} ${lname}`;
this.balance = minBalance;
this.account_number = account_number;
}
details() {
console.log(
`Cleint name: ${this.name} \n Balance: ${this.balance} \n Account number: ${this.account_number}`
);
}
isPositive(amount) {
return amount > 0 ? true : false;
}
isVlaidAmount(amount) {
return isNaN(amount) || !this.isPositive(amount) ? false : true;
}
deposit(amount) {
if (this.isVlaidAmount(amount)) {
this.balance += amount;
} else {
console.log("Sorry, this transcation cannot be completed!");
}
}
withdraw(amount) {
if (this.isVlaidAmount(amount)) {
this.balance -= amount;
} else {
console.log("Sorry, you have insufficient funds.");
}
}
transfer(amount, reciever) {
if (this.isVlaidAmount(amount)) {
this.withdraw(amount);
reciever.deposit(amount);
}
}
}
// create objects
let acc1 = new BankAccount("George", "Omara", 422);
let acc2 = new BankAccount("Haward", "Walowets", 662);
public class AccountDriver {
public static void main(String[] args) {
// ID, Balance, Annual Interest Rate
Account number1 = new Account();
Account number2 = new Account(1122, 20000.00, 0.045);
// Default account
System.out.println("The Account ID is: " + number1.getId());
System.out.println("The Account Balance is: " + number1.getBalance());
// System.out.println("The Account Balance is: "+
// number1.getMontlyInterest());
System.out.println("");
// Ask to withdraw 2500
System.out.println("The Account ID is: " + number2.getId());
number2.withdraw(2500.00);
number2.deposit(3000.00);
System.out.println("Account Balance is " + number2.getBalance());
// System.out.println("The montly interest is : "+
// number2.getMontlyInterest());
System.out.println("");
}
}
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public Account(int id, double balance, double annualInterestRate) {
this.setId(id);
this.setBalance(this.balance);
this.setBalance(annualInterestRate);
}
public Account() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMontlyInterest(double montlyInterest) {
// Given Formula
// double MontlyInterest= this.balance * get.MontlyInterestRate();
return montlyInterest;
}
public double getMontlyInterestRate(double montlyInterestRate) {
// Given Formula
montlyInterestRate = this.annualInterestRate / 12;
return montlyInterestRate;
}
double withdraw(double amount) {
return balance -= amount;
}
double deposit(double amount) {
return balance += amount;
}
}
I am getting error
The Account ID is: 0
The Account Balance is: 0.0
The Account ID is: 1122
Account Balance is 20500.0
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getMontlyInterestRate(double) in the type Account is not applicable for the arguments ()
at Account.getMontlyInterest(Account.java:41)
at AccountDriver.main(AccountDriver.java:21)
You did 2 small mistakes in your code.
In your constructor these 2 lines
this.setBalance(this.balance); // this.balance is the instance variable and not the parameter passed
^^^^ - this is not required, just use the balance parameter passed.
this.setBalance(annualInterestRate); // you are re-writing the balance with interest rate
^^^^^^^^^^ - You need to set annual interest rate and not the balance here.
should be
this.setBalance(balance); // sets the balance passed to the instance variable balance
this.setAnnualInterestRate(annualInterestRate); // sets the annual interest rate
Now since the annualInterestRate is set, you can get the monthly interest rate by modifying getMontlyInterestRate method like this.
public double getMontlyInterestRate() {
// Given Formula
return this.annualInterestRate / 12;
}
And you can print your monthly interest rate by uncommenting your System.out.println code.
System.out.println("The montly interest is : "+ number2.getMontlyInterestRate());
And the monthly interest method would look like this:
public double getMontlyInterest() { // no parameter required
// Given Formula
double MontlyInterest = this.balance * getMontlyInterestRate(); // balance multiplied by monthly interest rate
return MontlyInterest; // return the value
}
System.out.println("The montly interest is : "+ number2.getMontlyInterest());
so I'm having an issue writing my code such that i will be able to create an equals method that will return true if 2 credit cards are equal if they have the same Security code, company and account number.
Heres my code so far.
public class CreditCard {
private double balance;
public static double interestRate;
public static String personname;
public static String company;
public static double creditLine;
public CreditCard ()
{
balance = 0;
}
public static void setIntRate (double rate)
{
interestRate = rate;
System.out.println("The Interest rate for this card is : " + interestRate);
}
public static double getIntRate ()
{
return interestRate;
}
public static void setPersonName (CreditCard card ,String pName)
{
personname = pName;
System.out.println("Name on card: " + personname);
}
public static void setCompany (CreditCard card, String compName)
{
company =compName;
System.out.println("The Company name is : "+ company);
}
//creates new card number
public static void CardNum (CreditCard card)
{
int[] accountnumber = new int [16];
Random generator = new Random ();
for (int i =0; i<16; i++)
accountnumber [i] = (int)(Math.random()*10);
System.out.println ("The Account number for this card is: " + (java.util.Arrays.toString(accountnumber))+"");
}
//Creates new securitycode
public static void getSecurityCode (CreditCard card)
{
int[] securitycode = new int [3];
Random generator = new Random ();
for (int i =0; i<3; i++)
securitycode [i] = (int)(Math.random()*10);
System.out.println ("The security code for this card is: " + (java.util.Arrays.toString(securitycode))+"");
}
public static void setexpirationdate(int MM, int YY)
{
System.out.println("The expiration date for this card is: " + MM + "/"+ YY + "\n");
}
public static void setCreditLine (int cLine){
creditLine =cLine;
}
public static void getCreditLine (CreditCard card)
{
System.out.println( " CreditLine is : $" + creditLine);
}
// buys something
public void buyWithCreditCard (double amount)
{
balance = balance + amount;
}
//Inserts money to reduce balance
public double paybalance (double amount)
{
if (balance >= amount){
balance = balance - amount;
roundBalance();}
else{
creditLine = creditLine + (amount - balance);
balance = 0;
System.out.println("Your new CreditLine is: "+creditLine);
roundBalance();
}
return amount;
}
// adds interest to balance
public void addInterest ()
{
double interest = balance * getIntRate ();
balance = balance + interest;
roundBalance ();
}
private void roundBalance ()
{
balance = (double)(Math.round(balance*100))/100;
}
public double checkBalance (){
return balance;
}
//Shows Credit Card Debt
public static void showBalance (CreditCard card)
{
System.out.print(card.balance);
}
}
and then the class that utilizes the CreditCard Class.
public class CreditCardDemo {
public static void main (String [] args)
{
//Creates cards 1 and 2
CreditCard firstCard = new CreditCard ();
CreditCard secondCard = new CreditCard ();
//Calls for card info 1
System.out.println("First card Information is:");
CreditCard.setPersonName(firstCard,"John White");
//CreditCard.getName(firstCard);
CreditCard.setCreditLine(600);
CreditCard.getCreditLine(firstCard);
CreditCard.setCompany(firstCard,"Visa");
CreditCard.setIntRate(0.02);
CreditCard.CardNum(firstCard);
CreditCard.getSecurityCode(firstCard);
CreditCard.setexpirationdate(11, 17);
//call for card info 2
System.out.println("Second card Information is:");
CreditCard.setPersonName(secondCard,"Jack Black");
CreditCard.setCreditLine(2600);
CreditCard.getCreditLine(secondCard);
//CreditCard.getName(secondCard);
CreditCard.setCompany(secondCard,"Discover");
CreditCard.setIntRate(0.02);
CreditCard.CardNum(secondCard);
CreditCard.getSecurityCode(secondCard);
CreditCard.setexpirationdate(10, 19);
//Purchases
System.out.println("\nYou bought something for $5.00");
firstCard.buyWithCreditCard (5.00);
System.out.println("You bought another item for $12.00");
firstCard.buyWithCreditCard(12.00);
System.out.println("You bought another item for $15.00");
firstCard.buyWithCreditCard(15.00);
System.out.println("You bought another item for $33.42");
firstCard.buyWithCreditCard(33.42);
//Display Current Balance
System.out.print("You currently owe: $");
CreditCard.showBalance(firstCard);
//Interest Adds onto it
if (firstCard.checkBalance () > 50.00){
System.out.println("\nInterest has been added");
firstCard.addInterest ();
System.out.print("Your new balance is : $");
CreditCard.showBalance(firstCard);
System.out.println("");
//Payment
System.out.println("You have overpaid your balance.");
firstCard.paybalance (70);
System.out.print("Your new balance is : $");
CreditCard.showBalance(firstCard);
}
}
}
So if anyone could show me how to create a method in the CreditCard class that would allow me to check if the firstCard and secondCard, that would be great. Thanks a bunch :)
If you use NetBeans, you can simply auto-generate the equals function (not sure about Eclipse). Other than that it boils down to overwriting the equals function of Object.
Make sure to check that both are of the same class and make sure to check for null. Java recommends to as well overwrite the hashCode function, however that depends on your use-case.
first of all, i'm not that advanced in java, but this seems simple enough still.
The problem here seems that the security code is never saved (the method getSecurityCode is void and all variables are only local)
Same goes for the company
nonetheless, here's an example, assuming you fixed that and made a method getCode that returns the code (as int) and a method getAccountNumber, that returns that number (as int). (and assuming it's no problem to make those methods public)
public boolean equals(CreditCard creditCard1, CreditCard creditCard2){
if (creditCard1 == null || creditCard2 == null)
return creditCard1 == creditCard2;
boolean equalCode = (creditCard1.getCode() == creditCard2.getCode());
boolean equalCompany = creditCard1.company.equals(creditCard2.company);
boolean equalAccountNumber = (creditCard1.getAccountNumber() == creditCard2.getAccountNumber());
return equalCode && equalCompany && equalAccountNumber;
}
It would be good practice to make the variables private and make some getters, but that's up to you.