Is any data field become "Static" without declaring it explicitly? [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have declared private data field without "static" modifier but when i called the data field from a method. compiler said a "static reference to the non-static method" only for one data filed "annualInterestRate" and other's seem okay.
I also declared other data with same manner but they have no problem. but in case of "annualInterestRate" data field it's give error.
import java.util.Date;
import java.util.Scanner;
public class Account {
private int id;
private double balance;
private double annualInterestRate;
private java.util.Date dateCreated;
public Account() {
}
public Account(int id, double balance, double interestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = interestRate;
dateCreated = new java.util.Date();
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getInterestRate() {
return annualInterestRate;
}
public java.util.Date getDate(){
return dateCreated;
}
public double getMonthlyInterestRate() {
double monthlyInterestRate = annualInterestRate/12.0;
return monthlyInterestRate;
}
public double getmonthlyInterest() {
double monthlyInterestRate = annualInterestRate/12.0;
return monthlyInterestRate*balance;
}
public void withdraw(double balance) {
this.balance-=balance;
}
public void deposit(double balance) {
this.balance+=balance;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int id;
double balance,interestRate,mir;
Scanner in = new Scanner(System.in);
id = in.nextInt();
balance = in.nextDouble();
interestRate = in.nextDouble();
Account Person = new Account(id, balance, interestRate);
Person.withdraw(2500.0);
Person.deposit(3000.0);
mir = getmonthlyInterest();
System.out.println(balance + " " + mir + " " + dateCreated);
}
}
expected to run smoothly

Correcting slightly your main method to use an instance of your Account class :
public static void main(String[] args) {
// TODO Auto-generated method stub
int id;
double balance,interestRate,mir;
Scanner in = new Scanner(System.in);
id = in.nextInt();
balance = in.nextDouble();
interestRate = in.nextDouble();
Account myPerson = new Account(id, balance, interestRate);
myPerson.withdraw(2500.0);
myPerson.deposit(3000.0);
mir = myPerson.getmonthlyInterest();
System.out.println(balance + " " + mir + " " + myPerson.getDate());
}

Related

Using One Object in Multiple Classes

I'm trying to use a setter/getter class in multiple classes to modify a single variable. I understand that I have to use the same object in order for this to work, but I'm unsure on how to make a single object accessible to multiple classes.
public class accountbalance {
private double balance;
//getter
public double getBalance() {
return balance;
}
//Setter
public void setBalance(double newBalance) {
this.balance = newBalance;
}
}
This is where I'm trying to use it first:
public class CreateAccount {
String name;
double social;
int pin;
public CreateAccount()
{
name = "null";
social = 0;
pin = 0;
}
public CreateAccount(String enteredName, double enteredSocial,int enteredPin, double value)
{
name = enteredName;
social = enteredSocial;
pin = enteredPin;
double accountnum = 87495;
accountbalance a1 = new accountbalance();
a1.setBalance(value);
System.out.println(name);
System.out.println(social);
System.out.println("Your new PIN is " + pin);
System.out.println("Your new account balance is " + (a1.getBalance()));
}
}
And then I'm trying to use it again here:
public class deposit {
double enteredAmt;
double amt;
public void deposit() {
System.out.println("Enter an amount to desposit: ");
Scanner in = new Scanner(System.in);
enteredAmt = in.nextDouble();
accountbalance ab1 = new accountbalance();
System.out.println("current balence: " + ab1.getBalance());
amt = ab1.getBalance() + enteredAmt;
ab1.setBalance(amt);
System.out.println("Your new balance is " + (ab1.getBalance()));
}
}
I believe what you're trying to do is use the Command Design Pattern.
If you changed your classes to look more like this, things might work a tad bit better.
public class Account {
// Please do not use SS for an identifier.
private String identifier;
private String name;
// Money needs to be stored in it's lowest common denominator.
// Which in the united states, is pennies.
private long balance;
public Account(String identifier, String name) {
this.identifier = identifier;
this.name = name;
this.balance = 0L;
}
public String getIdentifier() {
return this.identifier;
}
public String getName() {
return this.name;
}
public long getBalance() {
return balance;
}
public void credit(long amount) {
balance =+ amount;
}
public void debit(long amount) {
balance =- amount;
}
}
Then here would be your CreateAccountCommand. It is a bit anemic, but that is ok.
public class CreateAccountCommand {
private String identifier;
private String name;
public CreateAccount(String identifier, String name) {
// Identifier sould actually be generated by something else.
this.identifier = identifier;
name = name;
}
public Account execute() {
return new Account(identifier, name);
}
}
Here is your DepositCommand:
public class DepositCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.credit(amount);
}
}
WithdrawCommand:
public class WithdrawCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.debit(amount);
}
}
Then run everything:
public class Run {
public static void main(String... args) {
CreateAccountCommand createAccountCommand = new CreateAccountCommand("12345678", "First_Name Last_Name");
Account account = createAccountCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Deposit $100.00
DepositCommand depositCommand = new DepositCommand(account, 10000);
depositCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Withdraw $75.00
WithdrawCommand withdrawCommand = new WithdrawCommand(account, 7500);
withdrawCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
}
}

Wrong output when creating an account (Object)

I'm having issues with my program which is a subclass of another program I wrote called account. I create an account (george) and set values to it, a string for name, int id, and double balance. I'm not getting any errors but the only correct value is the string for name. I think it has to do something with my Overridden toString() method in the account class not grabbing the correct values.
My output:
Account holder name: George
Account id: 0
Annual interest: 1.5
Monthly Interest Rate: 0.00125
Balance 109.0
Transaction:
Correct ouput:
Account holder name: George
Account id: 1122
Annual interest: 0.015
Monthly Interest Rate: 0.013862499999999998
balance: 1109.0
Transaction:
type: d amount: 30.0 balance: 1030.0 deposit
type: d amount: 40.0 balance: 1070.0 deposit
type: d amount: 50.0 balance: 1120.0 deposit
type: w amount: 5.0 balance: 1115.0 withdrawal
type: w amount: 4.0 balance: 1111.0 withdrawal
type: w amount: 2.0 balance: 1109.0 withdrawal
CustomerAccount.class :
public class CustomerAccount extends Account {
public static String name;
public static void main(String[] args) {
// TODO Auto-generated method stub
CustomerAccount george = new CustomerAccount("George", 1122, 1000.0);
george.setannualInterest(1.5);
Account c1 = george;
george.deposit(30);
george.deposit(40);
george.deposit(50);
george.withdraw(5);
george.withdraw(4);
george.withdraw(2);
System.out.println(c1.toString());
CustomerAccount john = new CustomerAccount("John", 1123, 500);
john.setannualInterest(2.5);
Account c2 = john;
ArrayList<CustomerAccount> sort = new ArrayList<CustomerAccount>();
//sort.add(c1);
//sort.addAll(c2);
}
CustomerAccount(String name, int id, double balance) {
this.name = name;
id = getId();
balance = getBalance();
}
ArrayList<Transaction> transactions = new ArrayList<Transaction>();
}
Transaction class:
class Transaction extends Account {
private java.util.Date dateCreated;
private char type;
private double amount;
private double balance;
private String description;
private double transaction;
Transaction() {
}
Transaction(char type, double amount, double balance, String description) {
dateCreated = new java.util.Date();
this.type = type;
this.amount = amount;
this.balance = balance;
this.description = description;
}
public String getDateCreated() {
return dateCreated.toString();
}
public char getType() {
return type;
}
public double getAmount() {
return amount;
}
public double getBalance() {
return balance;
}
public String getDescription() {
return description;
}
public double getTransaction() {
return this.transaction;
}
public void setType(char type) {
this.type = type;
}
public void setAmount(double amount) {
this.amount = amount;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setDescription(String description) {
this.description = description;
}
public void setTransaction(double amount) {
this.transaction = amount;
}
}
Account.class :
class Account {
private int id = 0;
private double balance = 0.0;
private double annualInterestRate = 0.0;
private java.util.Date dateCreated;
// set dateCreated for the time and date the account was created
Account() {
dateCreated = new java.util.Date();
}
// Set accounts id and balance equal to this objects
Account(int id, double balance){
this();
this.id = id;
this.balance = balance;
}
// Getters and Setters manipulating variables to be set to the created account
// Setters have no return value and set itself equal to the variable and getters
// grab the variables and return them.
public int getId() {
return this.id;
}
public double getBalance() {
return this.balance;
}
public double getannualInterestRate() {
return this.annualInterestRate;
}
public String getDateCreated() {
return this.dateCreated.toString();
}
public void setId(int id) {
this.id = id;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setannualInterest(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMonthlyInterestRate() {
return (annualInterestRate / 100) / 12;
}
public double getMonthlyInterest() {
return balance * getMonthlyInterestRate();
}
// set balance of withdraw to balance - amount = balance
public void withdraw (double amount) {
if(amount < balance) {
balance -= amount;
}
}
// set balance of deposit to balance + amount = balance
public void deposit(double amount) {
balance += amount;
//Transaction.add(new Transaction('D', amount, balance, "Deposit to account"));
}
#Override
public String toString() {
return "Account holder name: " + CustomerAccount.name +
"\nAccount id: " + id +
"\nAnnual interest: " + this.getannualInterestRate() +
"\nMonthly Interest Rate: " + this.getMonthlyInterestRate() +
"\nBalance " + this.getBalance() +
"\nTransaction: ";
}
}
To set the values in the Account class, you need to call
super(id, balance)
in the CustomerAccount constructor to call the constructor for Account
Try that

my getAverageBalance method always returns 0

So I have an Account class, and a TestAccount class. In the TestAccount class I need to call my getAverageBalance method to find the average balance of all the accounts I have created. Here is the code for my average balance method:
public static double getAverageBalance()
{
if (numberOfAccounts > 0)
return totalValueOfAccounts / numberOfAccounts;
else
return 0;
}
The problem is, it is always returning false on the if statement and I don't know why. Here is the rest of my account class code
public class Account
{
private int id;
private double balance;
private static double annualInterestRate;
private java.util.Date dateCreated;
private static int numberOfAccounts;
private static double totalValueOfAccounts;
public Account()
{
dateCreated = new java.util.Date();
}
public Account(int newId, double newBalance, double newAnnualInterestRate)
{
this.id = newId;
this.balance = newBalance;
dateCreated = new java.util.Date();
this.annualInterestRate = newAnnualInterestRate;
}
public int getId()
{
return this.id;
}
public double getBalance()
{
return balance;
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public static double getNumberOfAccounts()
{
return numberOfAccounts;
}
public static double getTotalValueOfAccounts()
{
return totalValueOfAccounts;
}
public void setId(int newId)
{
this.id = newId;
}
public void setAnnualInterestRate(int newAnnualInterestRate)
{
this.annualInterestRate = newAnnualInterestRate;
}
public void setBalance(double newBalance)
{
this.balance = newBalance;
}
public static void setAnnualInterestRate(double newAnnualInterestRate)
{
annualInterestRate = newAnnualInterestRate;
}
public double getMonthlyInterest()
{
return this.balance * (annualInterestRate / 1200);
}
public java.util.Date getDateCreated()
{
return this.dateCreated;
}
public void withdraw(double amount)
{
this.balance -= amount;
}
public void deposit(double amount)
{
this.balance += amount;
}
public void awardMonthlyInterestRate()
{
this.balance += getMonthlyInterest();
}
public void closeAccount()
{
System.out.println("Closing account " + id);
this.numberOfAccounts -= 1;
this.totalValueOfAccounts -= balance;
}
Here is the testaccount code:
public class TestAccount
{
public static void printAccount(Account acct)
{
System.out.printf("%5d $%9.2f %5.2f%% %29s\n\n", acct.getId(), acct.getBalance(), acct.getAnnualInterestRate(), acct.getDateCreated());
}
public static void main(String[] args)
{
System.out.println("The average account balance is: " + Account.getAverageBalance());
System.out.println();
Account a = new Account();
System.out.println("Default account: ");
printAccount(a);
a.setId(1122);
a.setBalance(20000);
a.setAnnualInterestRate(4.5);
System.out.println("Modified account: ");
printAccount(a);
a.withdraw(2500);
a.deposit(3000);
System.out.println("After withdraw and deposit: ");
printAccount(a);
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
a.awardMonthlyInterestRate();
System.out.println("After 6 months of interest: ");
printAccount(a);
System.out.println("The average account balance is: " + Account.getAverageBalance());
a.closeAccount();
System.out.println();
Account[] accts = new Account[5];
for (int i = 0; i < accts.length; i++)
{
accts[i] = new Account(i+1, (double) Math.floor(Math.random()*100000), 3.0 );
}
System.out.println("Array of five accounts with random balances:");
for (int i = 0; i < accts.length; i++)
{
printAccount(accts[i]);
}
System.out.println("The average account balance is: " + Account.getAverageBalance());
System.out.println();
System.out.println("Array after awarding 6 months of interest: ");
for (int i = 0; i < accts.length; i++)
{
Account b = accts[i];
for (int j = 0; j < 6; j++)
{
b.awardMonthlyInterestRate();
}
printAccount(accts[i]);
}
System.out.println("The average account balance is: " + Account.getAverageBalance());
}
}
I think perhaps you are missing a line inside your constructor:
public Account() {
dateCreated = new java.util.Date();
numberOfAccounts++;
}
If you never increment numberOfAccounts, I am not sure how you expect to ever get a value above 0. This is particularly unfortunate because that variable is private, so only a method of Account even has a chance of setting it.
You need to add the same line to your second constructor, but you can simplify by calling the first constructor. You also need to add to your totalValueOfAccounts.
public Account(int newId, double newBalance, double newAnnualInterestRate)
{
this(); // call the first constructor
this.id = newId;
this.balance = newBalance;
this.annualInterestRate = newAnnualInterestRate;
totalValueOfAccounts += newBalance;
}
You also need to update the variable totalValueOfAccounts inside every method that modifies an individual balance, such as the following:
public void setBalance(double newBalance)
{
totalValueOfAccounts -= this.balance;
totalValueOfAccounts += newBalance;
this.balance = newBalance;
}

Constructors for subclasses

Okay guys, im having trouble with these constructors for this code and some logic. I did most of it, just confused on how to finish this off.
Here is the main code i have. (it might be a little sloppy but its "good enough")
public class Accountdrv {
public static void main (String[] args) {
Account account = new Account(1122, 20000, 4.5);
account.withdraw(2500);
account.deposit(3000);
System.out.println("Balance is " + account.getBalance());
System.out.println("Monthly interest is " +
account.getMonthlyInterest());
System.out.println("This account was created at " +
account.getDateCreated());
}
}
class Account {
private int id;
private double balance;
private double annualInterestRate;
private java.util.Date dateCreated;
public Account() {
dateCreated = new java.util.Date();
}
public Account(int id, double balance, double annualInterestRate) {
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
dateCreated = new java.util.Date();
}
public int getId() {
return this.id;
}
public double getBalance() {
return balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setId(int id) {
this.id =id;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMonthlyInterest() {
return balance * (annualInterestRate / 1200);
}
public java.util.Date getDateCreated() {
return dateCreated;
}
public void withdraw(double amount) {
balance -= amount;
}
public void deposit(double amount) {
balance += amount;
}
}
Now, i wanted to create a Savings, and Checking account. I need help with what i need to add for constructors, i put in the comments the parts i know im missing but confused on how to do them.
Savings:
class Savings extends Account{
//need to create a constructor
public Savings(int id, double balance, double annualInterestRate) {
//need to invoke the constructor for Account
super(id, balance, annualInterestRate);
}
// need to override the withdraw method in Account
public void withdraw(double amount) {
// place logic to prevent the account from being overdrawn
// that is do not allow a negative balance
}
}
You just need to check id the amount < balance Or whatever logic you have (eg: you want
some threshold amount to be present in the account).
Also I would recommend to look into synchronized methods as you should synchronize access to account of a given user to ensure that when a withdraw function is invoked...another withdraw on the same user account has to wait...or else it will lead to problems...I will leave that to you to figure out.
public void withdraw(double amount) {
// place logic to prevent the account from being overdrawn
// that is do not allow a negative balance
if(balance < amount)
{
// print error message or do something
}
else
{
// withdraw the money
balance -= amount;
// print message or do something
}
}
super() invokes the constructor for the super-class, in the Savings case, Account.

Output not displaying anything [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So I have an assignment in Advanced Inheritance for Java and have the code pretty much hammered out but am having issues finishing it off and making it actually display the output. The program was split into 4 different parts and I have them listed below.
Account.java
public abstract class Account
{
protected long accountNumber;
protected double accountBalance;
public long getAccountNumber()
{
return accountNumber;
}
public double getAccountBalance()
{
return accountBalance;
}
public void setAccountNumber(long number)
{
number = accountNumber;
}
public void setAccountBalance(double balance)
{
balance = accountBalance;
}
public void setUpAccount(long number, double balance) //look up constructors
{
number = accountNumber;
balance = accountBalance;
}
public String toString()
{
return "Account Number: " + accountNumber + " Account Balance: " + accountBalance;
}
public abstract double computeInterest(int intPeriod);
}
Checkings.java
public class Checking extends Account
{
public String toString()
{
String info = "Checking\nAccount Number: " + accountNumber +
"\nAccount Balance: " + accountBalance ;
return info;
}
public Checking(long number)
{
number = accountNumber;
}
public double computeInterest(int intPeriod)
{
double total = ((accountBalance - 700) * .02) * 3;
return total;
}
}
Savings.java
public class Savings extends Account
{
private double interestRate;
public double getInterest()
{
return interestRate;
}
public void setInterest(double inter)
{
inter = interestRate;
}
public String toString()
{
String info = "Savings\nAccount Number: " + accountNumber + " \nAccount Balance: "
+ accountBalance + " \nInterest Rate: " + interestRate;
return info;
}
public Savings(long number, double interest)
{
number = accountNumber;
interest = interestRate;
}
public double computeInterest(int intPeriod)
{
double total = Math.pow((1 + interestRate), intPeriod) * accountBalance - accountBalance;
return total;
}
}
AccountArray.java
public class AccountArray
{
public static void main(String[] args)
{
Account[] refAccount = new Account[10];
/*refAccount[0] = new Checking(100);
refAccount[1] = new Checking(101);
refAccount[2] = new Checking(102);
refAccount[3] = new Checking(103);
refAccount[4] = new Checking(104);
refAccount[5] = new Savings(105, .02);
refAccount[6] = new Savings(106, .02);
refAccount[7] = new Savings(107, .02);
refAccount[8] = new Savings(108, .02);
refAccount[9] = new Savings(109, .02);
refAccount[0].setAccountBalance(1000.0);
refAccount[1].setAccountBalance(2000.0);
refAccount[2].setAccountBalance(3000.0);
refAccount[3].setAccountBalance(4000.0);
refAccount[4].setAccountBalance(5000.0);
refAccount[5].setAccountBalance(6000.0);
refAccount[6].setAccountBalance(7000.0);
refAccount[7].setAccountBalance(8000.0);
refAccount[8].setAccountBalance(9000.0);
refAccount[9].setAccountBalance(10000.0);*/
for(int inc = 0; inc < 10; inc++ )
{
refAccount[0] = new Checking(100);
refAccount[1] = new Checking(101);
refAccount[2] = new Checking(102);
refAccount[3] = new Checking(103);
refAccount[4] = new Checking(104);
refAccount[5] = new Savings(105, .02);
refAccount[6] = new Savings(106, .02);
refAccount[7] = new Savings(107, .02);
refAccount[8] = new Savings(108, .02);
refAccount[9] = new Savings(109, .02);
refAccount[0].setAccountBalance(1000.0);
refAccount[1].setAccountBalance(2000.0);
refAccount[2].setAccountBalance(3000.0);
refAccount[3].setAccountBalance(4000.0);
refAccount[4].setAccountBalance(5000.0);
refAccount[5].setAccountBalance(6000.0);
refAccount[6].setAccountBalance(7000.0);
refAccount[7].setAccountBalance(8000.0);
refAccount[8].setAccountBalance(9000.0);
refAccount[9].setAccountBalance(10000.0);
}
for(int ctr = 0; ctr < 10; ctr++)
{
System.out.println(refAccount[ctr].toString());
}
}
}
Is there something I'm like really obviously missing? It all compiles just fine but the output just displays 0s instead of the Account Numbers, Balance or Interest.
Any help would be very much appreciated since I'm running out of time.
All of your setter methods look the wrong way round, you've got them as...
public void setAccountNumber(long number)
{
number = accountNumber;
}
public void setAccountBalance(double balance)
{
balance = accountBalance;
}
All you're doing there is setting the parameter value, they should be...
public void setAccountNumber(long number)
{
accountNumber= number;
}
public void setAccountBalance(double balance)
{
accountBalance= balance;
}
You can make sure this doesn't happen my making your parameters final
Have a look at your constructors and setters You inverse your variable attribution
Ex
public void setAccountNumber(long number)
{
number = accountNumber;
}
should be
public void setAccountNumber(long number)
{
accountNumber = number;
}
same for all your setters and constructors

Categories