My problem is how do I add a value to a variable from another class, for example:
private int balance;
then later in the methods in the same class, I add values to the balance with no problem using:
balance += 50;
but when I go to another class, and type the object then the setter for the balance:
myObject.setBalance(50);
but the problem strikes here, when I go to the first class and return the balance from there, i get nothing (or the old value of balance) in other words, the NEW value of balance is not being added. Any ideas why? I've been stuck at this point for the last couple of hours
Here's my code:
public class Zoo
{
private int balance;
public void setBalance(int balance)
{
this.balance = balance;
}
public int getBalance()
{
return this.balance;
}
}
MY SECOND CLASS:
public class RandomEvents
{
private Zoo ZooBalance = new Zoo();
public void callEventSix()
{
System.out.println("A local group has raised money to your Zoo");
System.out.println("Would you like to accept the money? (y) or (n)");
Scanner readerEventThree = new Scanner(System.in);
String readerTwo = readerEventThree.next();
if ( readerTwo.equals("y") )
{
ZooBalance.setBalance(166);
System.out.println("You have accepted the gift");
System.out.println("Your new balance is " + ZooBalance.getBalance());
} else if ( readerTwo.equals("n") )
{
System.out.println("You have refused the gift");
}
}
}
In your case
Replace this line:
ZooBalance.setBalance(166);
with:
ZooBalance.setBalance(ZooBalance.getBalance() + 166);
Sytem.out.println(ZooBalance.getBalance()); // 166
You need to make a setter for that class. Assuming the name of the class is TestClass.
class TestClass {
private int balance = 50;
};
public int getBalance() {
return this.balance;
};
public void setBalance(int newBalance) {
this.balance = newBalance;
};
And then in another class:
TestClass test = new TestClass();
test.setBalance(test.getBalance() + 50);
System.out.println(test.getBalance);// 100
I'm pretty sure there's a difference between adding 50 to a value and setting a value to 50.
myObject.setBalance(50); will not add 50, it will change the value to 50. To add 50, you'd have to do something along the lines of myObject.setBalance(myObject.getBalance() + 50);
generally there are two ways to this.
First. Use getter and setter:
Zoo zoo = new Zoo();
zoo.setBalance(zoo.getBalance() + 50);
Second. Add an adder method:
public void addToBalance(int addend) {
balance += addend;
}
Zoo zoo = new Zoo();
zoo.addToBalance(50);
Related
public class Account {
double currentBalance;
Account(double currentBalance) {
this.currentBalance = currentBalance;
}
double getBalance() {
return(this.currentBalance);
}
void deposit(double amount) {
this.currentBalance += amount;
}
void withdraw(double amount) {
this.currentBalance -= amount;
}
public String toString() {
return("Your current account balance is: $" + this.currentBalance);
}
}
public class SavingsAccount extends Account {
double interestRate;
SavingsAccount(double interestRate, double amount) {
super(amount);
this.interestRate = interestRate;
}
void addInterest(double interestRate) {
this.currentBalance = this.currentBalance + (this.currentBalance * (interestRate / 100));
}
public String toString() {
return("Your current account balance is: $" + this.currentBalance + ". Your interest rate is: " + this.interestRate + "%");
}
}
public class AccountTester {
public static void main(String[] args) {
System.out.println("Welcome to the COMP 251 BANK");
Account[] acc = new Account[10];
acc[0] = new Account (100000); // initial amount of 100k
System.out.println(acc[0].toString());
acc[0].deposit(50000); //deposit 50k
System.out.println("Current balance after depositing is: " + "$" + acc[0].getBalance());
acc[0].withdraw(10000);
System.out.println("Current balance after withdrawing is: " + "$" + acc[0].getBalance());
System.out.println();
System.out.println("CHECKING ACCOUNT");
acc[1] = new CheckingAccount(10000,50000); //overdraft limit of 1000, initial amount of 50k
System.out.println(acc[1].toString());
acc[1].deposit(20000); //I dont know what to do about the chequeDeposit
System.out.println("Current balance after depositing is: " + "$" + acc[1].getBalance());
System.out.println();
System.out.println("SAVINGS ACCOUNT");
acc[2] = new SavingsAccount(10, 50000);
System.out.println(acc[2].toString());
acc[2].deposit(10000);
System.out.println("Current balance after depositing is: " + "$" + acc[2].getBalance());
acc[2].addInterest();
}
}
I'm still new to this so I'm sorry if this is a bad question but I tried playing around with each class and I still can't figure out how to use the addInterest method I created in the SavingsAccount class that extends the Account class. I tried SavingsAccount.addInterest but I get a static reference error. I thought acc[2].addInterest would work but it says its undefined for the type Account.
You need to cast acc[2] to SavingsAccount before calling the method.
((SavingsAccount) acc[2]).addInterest();
It is called downcasting and here is an explanation of it.
You're trying to invoke a child class' method, addInterest from a base class reference.
In fact, your array has been declared as an array of Account objects
Account[] acc = new Account[10];
This class does not offer the addIntereset method, even though your arr[2] contains a SavingAccount instance, Java in fact will only be able to know this at run-time. At compile time, your syntax must be compliant with the declared type (Account).
To work around this problem you have two solutions: creating a generic addInterest method in your base class which your child classes will override or cast your arr[2] to a SavingAccount instance.
With the first approach, you're offering an addInterest method from the base class, so whatever instance is going to call the method (an actual Account or a subtype), it will always be able to invoke it.
public class Account {
public void addInterest(double interest){
//Account implementation
}
}
public class SavingAccount {
#Overrride
public void addInterest(double interest){
//SavingAccount implementation
}
}
So, in your main you could type with no errors:
Account[] arr = new Account[10];
arr[0] = new Account();
arr[0].addInterest(5); //No error, dynamic dispatch will call Account's implementation
arr[1] = new SavingAccount();
arr[1].addInterest(10); //No error, dynamic dispatch will call SavingAccount's implementation
With the second approach instead, you need to make sure that what you're downcasting corresponds to the subtype of your casting.
//Randomly assigning to acc an Account instance or a SavingAccount instance
Account acc = Math.round(Math.random()) == 0 ? new Account() : new SavingAccount();
//Making sure to downcast acc to SavingAccount with the instanceof operator
if (acc instanceof SavingAccount){
SavingAccount savAcc = (SavingAccount) acc;
savAcc.addInterest(5);
}
I am a beginner in Java and I hit a small snag.
I'm writing some code for an imaginary bank, and I want to include all the accounts' balance into one if statement. I made a double called accountBalance that I use for each account.
For example, Josie.accountBalance = 1200. Josie is an object for the BankAccounts type I created.
I want to make an if statement, so that if the account balance is above 1000, the bank sends a message warning the account about this issue, and it refunds everything above 1000$.
I could just do an if statement for every account I create, and write my code there, but I was wondering if there was a way to write an if statement that applied to all the BankAccounts type, without having to specify the names.
Thanks.
Here's the code that I wrote.
package learnJavaNew;
import java.util.ArrayList;
public class BankAccounts {
final static double defaultBalance = 50;
final static double maxBalance = 1000;
static double oldBalance;
static int employees;
static double bankMoney;
static double accountBalance;
static double newBalance;
public static void main(String[] args) {
// Josie's Bank Account
BankAccounts Josie = new BankAccounts();
Josie.depositMoney(0);
Josie.accountBalance = defaultBalance + newBalance;
System.out.println(Josie.accountBalance);
Josie.withdrawMoney(25.64);
Josie.accountBalance = defaultBalance + newBalance;
System.out.println(Josie.accountBalance);
// Dan's Bank Account
BankAccounts Dan = new BankAccounts();
Dan.depositMoney(1000);
Dan.accountBalance = defaultBalance + newBalance;
System.out.println(Dan.accountBalance);
Dan.withdrawMoney(5);
Dan.accountBalance = defaultBalance + newBalance;
System.out.println(Dan.accountBalance);
// Accounts List
ArrayList<BankAccounts> accounts = new ArrayList<BankAccounts>();
accounts.add(Josie);
accounts.add(Dan);
System.out.println(accounts);
// Max Balance
if(accountBalance >= maxBalance) {
System.out.println("You have reached the maximum balance for your bank account, which is " + maxBalance + "$.");
System.out.println("You cannot deposit more money into this account.");
oldBalance = accountBalance;
accountBalance = 1000;
System.out.println("You have been refunded " + (oldBalance - accountBalance));
}
// New Balance
System.out.println(Dan.accountBalance);
System.out.println(Josie.accountBalance);
}
public void depositMoney(double depositedMoney) {
newBalance = depositedMoney;
}
public void withdrawMoney(double withdrawnMoney) {
newBalance = newBalance - withdrawnMoney;
}
}
This kind of depends on the result you want. If the above code gives you the right result, then it's fine. However I would probably do something like this, and omit the loop and the list entirely.
public void depositMoney(double depositedMoney) {
if( depositedMoney + accountBalance > 1000 )
System.out.println( "Maximum exceeded, not processed" );
else
accountBalance += depositedMoney;
}
Notice here that I've changed the previous operation of depositedMoney, including the fact that the method never updated accountBalance.
To refund money over an amount, you might return a value indicating the amount refunded.
public double depositMoney(double depositedMoney) {
double refund = 0;
if( depositedMoney + accountBalance > 1000 ) {
refund = depositedMoney + accountBalance - 1000;
accountBalance = 1000;
System.out.println( "Maximum exceeded, refund " + refund );
}
else
accountBalance += depositedMoney;
return refund;
}
Also, you really should be using instance variables. Remove the static keyword.
double bankMoney;
double accountBalance;
double newBalance;
This might be made clearer by a different object model.
I would propose a BankAccount class (not "a BankAccounts class" -- that would mean that an object is "a BankAccounts", a jarring concept) and a Bank class.
class BankAccount {
private String owner;
private double balance;
BankAccount(String s, double b) { owner = s; balance = b; }
String owner() { return owner; }
double balance() { return balance; }
void deposit(double amount) { … like before … }
void withdraw(double amount) { … like before … }
}
and
class Bank {
static List<BankAccount> accounts = new ArrayList<>();
public static void main(String[] args) {
// set up some accounts
BankAccount josie = new BankAccount("Josie", 0);
accounts.add(josie);
BankAccount dan = new BankAccount("Dan", 1000);
accounts.add(dan);
:
etc
:
// print them all
double total = 0;
for (BankAccount acnt : accounts) {
System.out.printf("Account %s : balance %s %n",
acnt.owner(), acnt.balance());
total += acnt.balance();
}
System.out.printf("Total value of accounts: %s %n", total);
}
}
The benefit of this approach is that it makes it clearer what operations are for a single account and what operations are on "all accounts".
I am trying to write a java program which have two classes. The second class will have the main method and for checking the balance of the account and. The first class will have three methods one for opening an bank account, one for deposit and one for withdrawal. All input needs to be given by user. I am new to java and stuck after at one point any help would be appreciated.
import java.util.Scanner;
class Balance {
static int account()
{ Scanner minimumAmount = new Scanner(System.in);
int openingAmount = minimumAmount.nextInt();
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account:" + openingAmount);
if (openingAmount > 1000)
{
System.out.println("Your Bank account has opened successfully");
int ac = minimumAmount.nextInt();
System.out.println("Enter your account number" + ac);
}
}
static int withdrawal() {
Scanner withdrawalAmount = new Scanner(System.in);
int w = withdrawalAmount.nextInt();
System.out.println("Withdrawal Amount is :" + w);
int b = openingAmount - w;
if (b < 100) {
System.out.println("Unable to process your request");
}
}
void deposit() {
Scanner depositAmount = new Scanner(System.in);
int d = depositAmount.nextInt();
System.out.println("Deposited amount is :" + d);
int b = openingAmount + d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
}
}
i) Is there a way where an user input variable declared under one method can be used in another method to declare another variable?
ii) ow to return a value from a method so that the value received works in different method while declaring a variable?
Is there a way where an user input variable declared under one method
can be used in another method to declare another variable?
You can declare your attribute in your class and use constructor to initialize it for example :
class A{
private String name;
public A(String name){
this.name = name
}
public int account(){
//can use and change the name
}
public int withdrawal(){
//can use and change the name
}
public int deposit(){
//can use and change the name
}
}
Main class
public class B{
public static void main(String[] args) {
A s = new A("Hello");
//------------^^---pass your attribute in the constructor
s.account();
s.withdrawal();
s.deposit();
}
}
How to return a value from a method so that the value received works
in different method while declaring a variable?
You can use the result of each method in another method for example :
s.withdrawal(s.account());
//--------------^^-------account return a result that can be used by withdrawal
I don't know what you really want to do, but I can explain some things.
Methods account() & withdrawal() don't have to be static.
You can use instance attribute like I do to store values.
Balance & AccountBalance should be in different files.
Take a look about private & public on attribut & methods (& getter/setter)
Scanner is a little bit tricky so you should declare it once, and reuse it.
If you want to use returned value from function, change void by int (in this case) and use "return var" (var is what you want to return). So when you can call the function like this -> int value = s.account();
Try this code, it works.
Cheers !
import java.util.Scanner;
class Balance {
private Scanner scanner;
public int userAccount;
public int userAccountNumber;
public Balance() {
scanner = new Scanner(System.in);
}
public void account() {
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account : ");
int openingAmount = scanner.nextInt();
if (openingAmount > 1000) {
System.out.println("Your Bank account has opened successfully");
userAccount = openingAmount;
System.out.println("Enter your account number : ");
userAccountNumber = scanner.nextInt();
} else {
System.out.println("Not enought money");
this.account(); //Ask again for opening an account
}
}
public void withdrawal() {
System.out.println("Withdrawal Amount is : ");
int w = scanner.nextInt();
int b = userAccount - w;
if (b < 100) {
System.out.println("Unable to process your request");
} else {
userAccount = b;
}
}
public void deposit() {
System.out.println("Deposited amount is : ");
int d = scanner.nextInt();
userAccount += d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
System.out.println("Final amount is : "+s.userAccount);
}
}
I'm having a little bit of trouble with my code that I can't seem to figure out. Whenever I run this, it prints "Customer is null" instead of inserting their name. It also always calculates all tax as 0 (something wrong with my if statement?).
Is there any chance you guys can spot the issue? It seems as though everything else works correctly. (Wrote methods in Customer class, calling them in TestCustomer class, and the instructions are at the end of the post).
Thank you for anyone who takes the time to read this and attempt to help. Sorry for so much information, I just have no clue what is causing this, so I figured I'd include everything.
Customer class
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Customer {
public static double taxRate = 0.00;
public static double saleRate = 0.00;
String customerName;
double listSaleAmount;
double saleDiscount = 0;
double netSaleAmount;
double taxAmount;
double saleTotal;
boolean taxable;
public double total;
public Customer (String customerName, boolean taxable) {
}
public void calculateTax () {
saleDiscount = listSaleAmount*(saleRate/100);
netSaleAmount = listSaleAmount-saleDiscount;
if (taxable = true){
taxAmount = netSaleAmount*(taxRate/100);
}
else{
taxAmount = 0;
}
saleTotal = netSaleAmount + taxAmount;
total += saleTotal;
}
public void printRecord () {
System.out.println("Customer is " + customerName);
System.out.println("Sale amount is $" + listSaleAmount);
System.out.println("Discount amount is $" + saleDiscount);
System.out.println("Net Sale Amount is $" + netSaleAmount);
System.out.println("Tax amount is $" + taxAmount);
System.out.println("Total Sale Amount is $" + saleTotal);
System.out.println(" ");
}
public static void changeTaxAmount () {
Scanner input = new Scanner(System.in);
double userTaxAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Tax Rate? (8.25 & 8.50 for testing)"));
taxRate = userTaxAmount;
}
public static void changeSaleRate () {
Scanner input = new Scanner(System.in);
double userSaleAmount = Double.parseDouble(JOptionPane.showInputDialog("What is the Sale Discount Rate? (0.00 & 7.50 for testing)"));
saleRate= userSaleAmount;
}
public static void printTaxRate() {
System.out.println("Tax Rate is " + taxRate + "%.");
}
public static void printSaleRate() {
System.out.println("The Sale Rate is " + saleRate + ".");
System.out.println(" ");
}
}
TestCustomer class
public class TestCustomer {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customer1 = new Customer("Annie Smith", true);
Customer customer2 = new Customer("Bob Wilson", false);
Customer.changeTaxAmount();
Customer.printTaxRate();
Customer.changeSaleRate();
Customer.printSaleRate();
customer1.listSaleAmount = 65.00;
customer2.listSaleAmount = 52.00;
customer1.calculateTax();
customer1.printRecord();
customer2.calculateTax();
customer2.printRecord();
Customer.changeTaxAmount();
Customer.printTaxRate();
Customer.changeSaleRate();
Customer.printSaleRate();
customer1.listSaleAmount = 84.00;
customer2.listSaleAmount = 105.00;
customer1.calculateTax();
customer1.printRecord();
customer2.calculateTax();
customer2.printRecord();
double total2 = customer1.total + customer2.total;
System.out.println("The total of all sales is $" + total2);
}
}
Assignment sheet (Not worrying about printing to a file right now, just want the main mechanics to work)
Also, thank you to those of you who helped me with my last question on this project. You helped a lot.
In your constructor
public Customer (String customerName, boolean taxable) {
}
You are passed in parameters, but you never assign them to your class fields.
try
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
You have to define your constructor in customer class to set values of customerName and texable class level variables:
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
Also, there seems to be problem with the below if condition:
if (taxable = true){
You should use == operator for comparing:
if (taxable == true) {
Actually, you don't need to compare it. Just use:
if (taxable) {
Your constructor in Customer class should assign the name and taxable value to Customer data member.
public Customer (String customerName, boolean taxable) {
this.customerName = customerName;
this.taxable = taxable;
}
Instead of using if (taxable = true), simply use if (taxable).
The problem is the following:
(Savings Account Class) Create class SavingsAccount. Use a static
variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance
variable savingsBalance indicating the amount the saver currently has
on deposit. Provide method calculateMonthlyInterest to calculate the
monthly interest by multiplying the savingsBalance by
annualInterestRate divided by 12—this interest should be added to
savings- Balance. Provide a static method modifyInterestRate that sets
the annualInterestRate to a new value. Write a program to test class
SavingsAccount. Instantiate two savingsAccount objects, saver1 and
saver2, with balances of $2000.00 and $3000.00, respectively. Set
annualInterestRate to 4%, then calculate the monthly interest for each
of 12 months and print the new balances for both savers. Next, set the
annualInterestRate to 5%, calculate the next month’s interest and
print the new balances for both savers.
I solved it all, but the balance is not incrementing -- it is staying the same. It should increment with every change in annual interest rate (at least, that's what I understood).
class SavingsAccount
{
static double annualInterestRate;
private double savingsBalance;
public SavingsAccount(double balance)
{
savingsBalance = balance;
}
public double calculateMonthlyInterest()
{
return (savingsBalance*annualInterestRate)/12;
}
public static void modifyInterestRate(double rate)
{
annualInterestRate = rate;
}
public static double getannualInterestRate(){return annualInterestRate;}
public double getsavingsBalance(){return savingsBalance;}
}
public class SavingsTest
{
public static void main(String args[])
{
SavingsAccount saver1 = new SavingsAccount(2000.0);
SavingsAccount saver2 = new SavingsAccount(3000.0);
SavingsAccount.modifyInterestRate(4);
System.out.printf("Balance for Saver1 = %.2f\nBalance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance()+saver1.calculateMonthlyInterest(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
SavingsAccount.modifyInterestRate(5);
System.out.printf("New Balance for Saver1 = %.2f\nNew Balance for Saver2 = %.2f\nInterest Rate = %.2f\n\n",saver1.getsavingsBalance(),saver2.getsavingsBalance(),SavingsAccount.getannualInterestRate());
}
}
You are not modifying the value of savingsBalance in this code.
public double addMonthlyInterest() {
savingsBalance += (savingsBalance*annualInterestRate)/12;
return savingBalance;
}
This will return the new balance and 'increment'
In your first print statement, for the first argument you are calculating the balance after calculating the monthly interest and adding them together and didn't set the new value as the value of the class member savingsBalance.
In your second print statement, since you did not set the calculated value back to the class member through a setter, it is simply printing out the original value that the classes were instantiated with.
On a side note, don't do inline calculations in print statements. They are confusing and not easy to read for anyone. A good way is to initialize local members in the method and using them for calculations and printing the local members.
Just wanted to share my answer.
public class SavingsAccount {
private static float annualInterestRate = 0f;
private float savingsBalance;
public SavingsAccount(float balance) {
savingsBalance = balance;
}
public static void setAnnualInterestRate(float t) {
if (t >= 0 && t <= 1)
annualInterestRate = t;
else
throw new IllegalArgumentException("Annual interest rate should be between 0 and 1");
}
private float calculateMonthlyInterest() {
return savingsBalance * annualInterestRate / 12;
}
public float getSavingsBalance() {
return savingsBalance + calculateMonthlyInterest();
}
public float getAnnualInterestRate(){
return annualInterestRate;
}
public String toString() {
return String.format("Balance: %.2f", getSavingsBalance());
}
}
in main
SavingsAccount s1 = new SavingsAccount(2000);
SavingsAccount s2 = new SavingsAccount(3000);
SavingsAccount.setAnnualInterestRate(0.04f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);
SavingsAccount.setAnnualInterestRate(0.05f);
System.out.println("S1: " + s1);
System.out.println("S2: " + s2);