Calling functions on my SavingsAccount object and printing the result - java

I have a SavingsAccount object and I am trying to use my functions to manipulate the balance of the account. Now I get no errors but no output. I have the feeling that I have done something wrong and I don't quite understand how to call my functions on the object.
If I try to print the output for one of the accounts I make I get a memory adress.
I got all kinds of different errors while tweaking and its finally error free. But still no output and I am afraid I got it quite wrong and its just buggy and I don't call my functions the right way, or my constructor is not coded as its ment to be.
public class SavingsAccount {
// Class
int balance;
int amountToDeposit;
int amountToWithdraw;
//Constructor
public SavingsAccount(int initialBalance, int deposit, int withdraw){
balance = initialBalance;
amountToDeposit = deposit;
amountToWithdraw = withdraw;
}
//Functions thats I wanna call
// Setting balance
public void checkBalance() {
System.out.println("Hello!");
System.out.println("Your balance is " + balance);
}
// Depositing amounts
public void deposit(int amountToDeposit) {
balance = balance + amountToDeposit;
System.out.println("You just deposited" + amountToDeposit);
}
// Withdrawing amounts
public int withdraw(int amountToWithdraw) {
balance = balance - amountToWithdraw;
System.out.println("You just withdrew" + amountToWithdraw);
return amountToWithdraw;
}
// Main
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
//Check balance
System.out.println(test); // Will give a memory adress
}
}
I would like to use my functions on the object I make and print the result.
Thanks for reading.

Hello you can implement toString to print the object as below:
package com.stuart.livealert;
public class SavingsAccount {
// Class
int balance;
int amountToDeposit;
int amountToWithdraw;
//Constructor
public SavingsAccount(int initialBalance, int deposit, int withdraw){
balance = initialBalance;
amountToDeposit = deposit;
amountToWithdraw = withdraw;
}
//Functions thats I wanna call
// Setting balance
public void checkBalance() {
System.out.println("Hello!");
System.out.println("Your balance is " + balance);
}
// Depositing amounts
public void deposit(int amountToDeposit) {
balance = balance + amountToDeposit;
System.out.println("You just deposited" + amountToDeposit);
}
// Withdrawing amounts
public int withdraw(int amountToWithdraw) {
balance = balance - amountToWithdraw;
System.out.println("You just withdrew" + amountToWithdraw);
return amountToWithdraw;
}
#Override
public String toString() {
return "{balance : " + balance + " deposit : " + amountToDeposit + " withdraw : " + amountToWithdraw + " }";
}
// Main
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
//Check balance
System.out.println(test); // Will give {balance : 5000 deposit : 200 withdraw : 100 }
}
}

You can call your functions in the constructor:
public SavingsAccount(int initialBalance, int deposit, int withdraw){
balance = initialBalance;
deposit(deposit);
withdraw(withdraw);
checkBalance();
}
Then you will see all the System.out messages without the need to change the main method.

I have the feeling that I have done something wrong and I don't quite
understand how to call my functions on the object.
You can call your methods with the variable name of a SavingsAccount, followed by a ".", and then the method you would like to call.
So, rather than
//Check balance
System.out.println(test); // Will give a memory address
You can do this, for example:
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
test.checkBalance();
}
or
public static void main(String[] args){
//Setting values, balance, deposit, withdraw.
SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
SavingsAccount test = new SavingsAccount(5000, 200, 100);
test.deposit(50);
test.checkBalance();
}
With that in mind, perhaps it makes more sense to only specify a starting balance when constructing a SavingsAccount. Hope this helps!

Related

Object oriented programming, getter is not getting private variable from another class

The program is supposed to calculate interest for 2 accounts after 12 and 24 months. This works fine. My issue is the getter/setter for interest rate do not work, so when the interest rate is saved as 0.1 in another class private variable I can't print it from main class.
public class testAccountIntrest{
//main method
public static void main(String[] args) {
//creating objects
Account account1 = new Account(500);
Account account2 = new Account(100);
//printing data
System.out.println("");
System.out.println("The intrest paid on account 1 after 12 months is " + account1.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 1 after 24 months is " + account1.computeIntrest(24));
System.out.println("");
System.out.println("");
System.out.println("The intrest paid on account 2 after 12 months is " + account2.computeIntrest(12));
System.out.println("");
System.out.println("The intrest paid on account 2 after 24 months is " + account2.computeIntrest(24));
System.out.println("");
System.out.println("The intrest rate is " + getIntrest());
}//end main method
}//end main class
class Account {
//instance variables
private double balance;
private double intrestRate = 0.1;
//constructor
public Account(double initialBalance) {
balance = initialBalance;
}
//instance methods
public void withdraw(double amount) {
balance -= amount;
}
public void deposit(double amount) {
balance += amount;
}
public double getBalance() {
return balance;
}
public void setIntrest(double rate) {
intrestRate = rate;
}
public double getIntrest() {
return intrestRate;
}
public int computeIntrest(int n) {
double intrest = balance*Math.pow((1+intrestRate),(n/12));
return (int)intrest;
}
}
As the compiler is undoubtedly telling you, your testAccountIntrest class doesn't have a method called getInterest(). So this alone can't do anything in the context of that class:
getInterest()
However, your Account class does have that method. And you have two Account objects in that scope:
Account account1 = new Account(500);
Account account2 = new Account(100);
So you can call that method on those objects:
account1.getInterest()
or:
account2.getInterest()
Basically, you have to tell the code which object you're calling the method on. It can't figure it out on its own.
getIntrest() is a member method, therefore you need to call
System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
System.out.println("The intrest rate for account 2 is " + account2.getIntrest());
To call a method from another class you need an object of another class.
So, you need an instance of account to call getIntrest. For example:
System.out.println("The intrest rate for account 1 is " + account1.getIntrest());
If an interest rate is the same for all accounts you can make it static:
private static double intrestRate = 0.1;
public static double getIntrest() {
return intrestRate;
}
Static fields belong to the class and you don't need a specific instance to access it:
System.out.println("The intrest rate for all accounts is " + Account.getIntrest());

Bank Account TransferTo Method

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);

Add numbers in JAVA

How do I add the deposit numbers? Do I need some kind of loop (I´m new to JAVA)?.
public class BankAccount {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000, "Deposit 1");
account.deposit(2000, "Deposit 2");
System.out.println("Balance: " + account.getBalance());
account.deposit(3000, "Deposit 3");
account.deposit(4000, "Deposit 4");
System.out.println("Balance: " + account.getBalance());
}
private int currentBalance = 0;
private int getBalance() {
int finalBalance = depositAmount + currentBalance;
return finalBalance;
}
private int depositAmount;
public void deposit(int depositAmount) {
this.depositAmount = depositAmount;
}
}
Result should be:
Balance: 3000
Balance: 10000
Your deposit function is suspect. I think you want:
public void deposit(int depositAmount) {
this.currentBalance += depositAmount;
}
Note the +=: this will accumulate the deposit amount. You should also get rid of the class member depositAmount which is also causing bugs. Your getBalance function then reduces to
private/*ToDo - this will probably be public eventually*/ int getBalance() {
return currentBalance;
}
Two more issues though:
This function deposit is not called directly since you are calling a version that also takes a string. (I'm assuming that the function you give is called eventually though).
How will you model decimal values? Don't use a floating point as that will be imprecise. Use a currency type instead.
Well, this might work for you
public class BankAccount {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.deposit(2000);
System.out.println("Balance: " + account.getBalance());
account.deposit(3000);
account.deposit(4000);
System.out.println("Balance: " + account.getBalance());
}
private int currentBalance = 0;
private int getBalance() {
return this.currentBalance;
}
public void deposit(int depositAmount) {
this.currentBalance = this.currentBalance + depositAmount;
}
}
You are actually adding everything to the same object account . hence you are getting the result of all values inside it .(i.e) sum of all inputs 10000

How to create an equals Method in Java for 2 credit cards

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.

Bank Account Program Issue

For my Java class, we need to make a bank account that has the methods of withdrawing, depositing money, and displaying current balance. In the Tester class, I want to make it ask for the name, the balance, then allow you to choose 1, 2, or 3. Then it repeats the option you choose until you say type "n". The problem is that running this code causes it to say after you deposit money "You deposited (amount of money deposited) in the account (name of account). Your new balance is (this)." The part where it says "this" is the exact same of the amount of money deposited. In other words, it doesn't add it, it just makes the new balance the same as the deposit, regardless of how much was in before. Any help? Thanks.
import java.io.*;
import java.util.*;
public class BankAccount
{
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
public void deposit(double d)
{
balance += d;
}
public void withdraw(double w)
{
balance -= w;
}
public String nickname()
{
System.out.print("Enter a new name: ");
Scanner kbIn = new Scanner(System.in);
String n = kbIn.nextLine();
return n;
}
double balance;
String name;
}
And the tester class:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbInLine = new Scanner(System.in);
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = kbInLine.nextLine();
System.out.print("Please enter balance: $");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(balance, name);
String proceed = "y";
while(proceed.equalsIgnoreCase("y"))
{
System.out.println("\nPlease pick a number. Would you like to...\n\t 1. Deposit\n\t 2. Withdraw\n\t 3. Print Balance\n");
int choice = kbIn.nextInt();
switch(choice)
{
case 1:
System.out.print("How much would you like to deposit?\n\t$");
double deposit = kbIn.nextDouble();
myAccount.deposit(deposit);
System.out.println("You have deposited $" + deposit + " into the account of " + name + ". The new balance is: " + myAccount.balance);
break;
case 2:
System.out.print("How much would you like to withdraw?\n\t$");
double withdraw = kbIn.nextDouble();
if(myAccount.balance - withdraw > 0)
{
myAccount.withdraw(withdraw);
System.out.println("You have withdrawn $" + withdraw + " from the account of " + name + ". The new balance is: " + myAccount.balance);
}
else
{
System.out.println("Sorry, you have insufficient funds for this operation. Your existing balance is $" + myAccount.balance);
}
break;
case 3:
System.out.print("The balance in the account of " + name + " is $" + myAccount.balance);
break;
}
System.out.print("\nWould you like to do another transaction? (Y/N)");
proceed = kbIn.next();
}
System.out.println("\nThank you for banking with us. Have a good day!");
}
}
What's really wierd is that I did a project before this one (it's actually a simplified version) where it deposits and then withdraws a predetermined, coded amount, then outputs the new bank balance, and it does it fine. But the code for BankBalance is the same. Here's the code for those.
BankAccount class is:
public class BankAccount
{
public BankAccount(String nm, double amt) // Constructor
{
name = nm;
balance = amt;
}
public void deposit(double d) // Sets up deposit object as balance += d
{
balance += d;
}
public void withdraw(double w) // Sets up withdraw object as balance -= w
{
balance -= w;
}
public double balance;
public String name;
}
And the Tester class is:
import java.io.*;
import java.util.*;
public class Tester
{
public static void main(String args[])
{
Scanner kbIn = new Scanner(System.in);
System.out.print("Enter your name:");
String name = kbIn.nextLine();
System.out.print("Enter the balance:");
double balance = kbIn.nextDouble();
BankAccount myAccount = new BankAccount(name, balance);
myAccount.deposit(505.22);
System.out.println(myAccount.balance);
myAccount.withdraw(100.00);
System.out.println("The " + myAccount.name + " account balance is, $" + myAccount.balance);
}
}
You're not actually initialising your balance member variable here:
public BankAccount(double b, String n)
{
double balance = b;
This creates a new local variable called balance, to which you assign the value of b. The member variable balance will remain 0 (the default) after this constructor is run.
public BankAccount(double b, String n)
{
double balance = b;
String name = n;
}
--->
public BankAccount(double b, String n)
{
this.balance = b;
this.name = n;
}
Or you can declare balance as static (data class field), and the methods that use this variable as static too.

Categories

Resources