I'm writing a program and I need to create accessor/mutator methods for the variable accountID.
This is what I have so far but I can't get past this "cannot be resolved to a variable" error when I create the accessor public int getAccountID(). How do I fix this error? I've looked for about an hour through other sources but none of them have helped which is why I've resorted to posting this specific question about it. Any help is appreciated.
import java.util.Scanner;
import java.util.Date;
public class Account {
public static void main(String[] args) {
int accountID = 0;
double balance = 0;
double annualInterestRate = 0;
Date dateCreated = new Date();
}
// default constructor that creates a default account
public Account() {
// fill this in later
}
// default constructor that creates an account
public Account(int accountID, double balance, double annualInterestRate) {
// fill this in later
}
// accessor for accountID
public int getAccountID() {
return accountID; // THIS IS WHERE I GET MY ERROR ~*~*~*~*~*~*~*~*~*~*~*
}
}
Your accountID (as well as the other variables defined in main) shouldn't be a local variable. It should be declared in the class level in order to be an instance variable, which will be accessible from all the non-static methods of your class.
public class Account {
private int accountID = 0;
private double balance = 0;
private double annualInterestRate = 0;
private Date dateCreated = new Date();
public static void main(String[] args)
{
...
}
....
}
Related
I have two classes, Main.java and Car.java
Main.java:
class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.efficiency);
}
}
Car.java:
class Car
{
public Car(double mpg, double initFuel)
{
double efficiency = mpg;
double fuel = initFuel;
}
}
I obviously tried to assign efficiency to the first constructor passed in when creating the object, but that doesn't seem to work (i.e. the variable is not found when I use the println in Main.java). How do I assign variables to objects to be referenced later?
You're using local variables in your Car's constructor. Their lifecycle bounded within your constructor. Just declare your members in your class and use getters and setters to access them.
class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
this.efficiency = mpg;
this.fuel = initFuel;
}
public void setEfficiency(double efficiency) {
this.efficiency = efficiency;
}
public double getEfficiency() {
return efficiency;
}
// Same thing for fuel...
}
And in your Main:
class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.getEfficiency());
}
}
Make efficiency and fuel global to your class rather than local to your constructor.
Main.java
public class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.efficiency);
}
}
Car.java
public class Car
{
public double efficiency;
public double fuel;
public Car(double mpg, double initFuel)
{
efficiency = mpg;
fuel = initFuel;
}
}
That should work. But you can make the instance variables private instead of public and use setters/getters
Also set your Main and Car to public so they can be accessible/instantiated from another class.
Main.java
public class Main
{
public static void main(String[] args)
{
Car ferrari = new Car(18, 25.43);
System.out.println(ferrari.getEfficiency());
}
}
Car.java
public class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
efficiency = mpg;
fuel = initFuel;
}
public double getEfficiency(){
return efficiency;
}
}
Change your Car class to:
class Car
{
private double efficiency;
private double fuel;
public Car(double mpg, double initFuel)
{
this.efficiency = mpg;
this.fuel = initFuel;
}
}
You need to declare the variables on the Class scope instead of the local scope when using a variable for an instantiated Object. These variables typically are set from the Constructor so they can be accessed later from the Object itself.
Most of the time these are also declared as private with a separate method to get and set them instead of directly accessing them.
Example:
public double getEfficiency(){
return this.efficiency;
}
public void setEfficiency(double mpg){
this.efficiency = mpg;
}
Most IDE's can auto generate Getters and Setters for you so you do not need to hand write them for every variable.
To use the getter/setter you call the method from an instance of the class rather than using the variable directly:
Car tesla = new Car(35.5, 90.5);
tesla.efficiency = 15.5; //YOU CAN'T DO THIS
tesla.setEfficiency(15.5); //Do this instead
System.out.println(tesla.getEfficiency()); //Will print 15.5
this might be something really easy to address but I am really new to Java and I am having a problem fixing this error. I am working on a basic ATM Machine (I can't go fancy just yet). I have a BankAccount class, a Checking Account (extends bankAccount), A savingsAccount class (also extends bankAccount) and a User class. In my CheckingAccount class, I want to use one of the parameters from my SUPER class (bankAccount), "balance" but I am not sure if there is a way to only use ONE parameter from a constructor that has more than One parameter. If so, any clue for how to? I am getting an Error : "no suitable constructor found for BankAccount(double)..." . This is my code so far, I appreciate your help.
-- BankAccount Class --
package atm;
public class BankAccount {
public double balance;
public int accountNumber = 333220;
public User user;
public BankAccount(){
balance = 0;
}
public BankAccount(double balance, int accountNumber, User user){
this.balance = balance;
this.accountNumber = accountNumber;
this.user = user;
}
public void accountNumber(){
accountNumber++;
}
public int getAccountNumber(){
return accountNumber;
}
public void deposit (double amount){
balance += amount;
}
public void withDraw(double amount) {
balance -= amount;
}
public double getBalance (){
return balance;
}
public void transfer( BankAccount other,double amount){
withDraw(amount);
other.deposit(amount);
}
}
-- CheckingAccount Class --
package atm;
public class CheckingAccount extends BankAccount {
private int transactionCount;
private static final double transactionFees = 1.50;
private static final int freeTransactions = 5;
public CheckingAccount (double balance){
super(balance); //HERE is where I am confused. I only need to use the "balance"
transactionCount = 0;
}
public void deposit(double amount){
transactionCount ++;
super.deposit(amount);
}
public void withDraw(double amount){
transactionCount ++;
super.withDraw(amount);
}
public void deductFees (){
if (transactionCount > freeTransactions){
double fees = transactionFees * (transactionCount - freeTransactions);
super.withDraw(fees);
}
transactionCount = 0;
}
}
Thanks a lot!
You need to create another constructor in BankAccount.java that only initializes amount like below
public BankAccount(double balance){
this.balance = balance;
}
Read about having multiple constructors in Java here
http://tutorials.jenkov.com/java/constructors.html
Since CheckingAccount is a BankAccount, it must have all the attributes of the BankAccount, including the account number and the User who owns it.
The base class requires accountNumber and user to be supplied by the derived class, so you should change the constructor to forward this information to super:
public CheckingAccount (double balance, int accountNumber, User user){
super(balance, accountNumber, user);
transactionCount = 0;
}
Note 1: In certain situations a derived class could hard-code parameters to be passed to super; this is not one of these situations.
Note 2: Consider making BankAccount abstract, and changing accessibility of its constructor from public to protected.
I have a problem with my program and I don't know why the names and the IDs of the objects don't show up right in the output and also the balance is not used in chkBalance() method Why ??I think the problem with the constructor but? ... and the output I get from this code is ...:
Customer Name Customer ID Balance
null 0.0 200
null 0.0 200
null 0.0 200
public class BankAccount {
private int Balance;
public String AccHolder_Name;
public double AccHolder_ID;
public BankAccount(String Name ,double ID,int Balance) {
Name = AccHolder_Name;
ID = AccHolder_ID;
}
public void withDraw(int a) {
Balance=a-Balance;
}
public void deposit(int b) {
Balance=b+Balance;
}
public int chkBalance(){
deposit(500);
withDraw(700);
return Balance;
}
public void Display () {
System.out.println(AccHolder_Name+"\t\t"+AccHolder_ID+"\t\t"+Balance);
}
public static void main (String args []) {
BankAccount o1=new BankAccount("Aos" , 1101558733 ,3000);
BankAccount o2=new BankAccount("Ahmed" , 1101978733,5000);
BankAccount o3=new BankAccount("Ali",1111650924,7000);
System.out.println("Customer Name\tCustomer ID\tBalance");
o1.chkBalance();
o2.chkBalance();
o3.chkBalance();
o1.Display();
o2.Display();
o3.Display();
}
}
In your constructor you are assigning null to the given parameters and never assign Balance
public BankAccount(String Name ,double ID,int Balance) {
Name = AccHolder_Name; // Will assign #AccHolder_Name to #Name
ID = AccHolder_ID;
}
So you should reverse this assignment and set the Balance field with the given parameter :
public BankAccount(String Name ,double ID,int Balance) {
AccHolder_Name = Name; // Will assign #Name to #AccHolder_Name
AccHolder_ID = ID;
this.Balance = Balance;
}
And about your variables names you should take a look to the naming convention.
The variables should use camel case and for good practice be well representative of their function.
So AccHolder_Name should be accHolderName for example.
Your assignments in the constructor is the wrong way arround. Also, you forgot to assign the Balance argument, which causes Balance to default to 0 and results in 200 after the calculations.
public BankAccount(String Name, double ID, int Balance) {
this.AccHolder_Name = Name;
this.AccHolder_ID = ID;
this.Balance = Balance;
}
An important note on your naming conventions: variables in Java use camel case. It is also discouraged to abbreviate variable names unless they are considered an abbreviation standard. The resulting code would then be:
public BankAccount(String name, double id, int balance) {
this.accountHolderName = name;
this.accountHolderId = id;
this.balance = balance;
}
The constructor of the BankAccount is indeed wrong. Since what '=' operation does is to give the value of the right variable to the left variable, and your code is reversed.
Another problem is that you don't initialize your Balance in your constructor and the compiler will then simply initialize it to 0.
Constructor has issue. Copy bellow code and replace your constructor and check.
public BankAccount(String Name ,double ID,int Balance) {
this.AccHolder_Name = Name;
this.AccHolder_ID = ID;
this.Balance = Balance;
}
My suggestion is to learn java more. Basic you can learn from Java Tutorial.
In the constructor you are assigning it in the other way. Assign it as below
public BankAccount(String Name ,double ID,int Balance) {
this.AccHolder_Name = Name;
this.AccHolder_ID = ID;
this.Balance = Balance;
}
There is always the variable you want to set on the left side and the value for it on the rigt side. As you want to set the String AccHolder_Name to the Name you are giving in the constructor, you have to do it just the other way around.
There are several mistakes:
a. Your constructor is incorrect and not saving the provided
variables.
this.AccHolder_Name=Name ;
this.AccHolder_ID=ID;
this.Balance=Balance;
b. Your withdraw method is incorrect. It should be (balance =
balance-a)
Please see the correct code below.
public class BankAccount {
private int Balance ;
public String AccHolder_Name;
public double AccHolder_ID;
public BankAccount(String Name ,double ID,int Balance) {
this.AccHolder_Name=Name ;
this.AccHolder_ID=ID;
this.Balance=Balance;
}
public void withDraw(int a) {
Balance=Balance-a;
}
public void deposit(int b) {
Balance=b+Balance;
}
public int chkBalance(){
deposit(500);
withDraw(700);
return Balance;
}
public void Display () {
System.out.println(AccHolder_Name+"\t\t"+AccHolder_ID+"\t\t"+Balance);
}
public static void main (String args []) {
BankAccount o1=new BankAccount("Aos" , 1101558733 ,3000);
BankAccount o2=new BankAccount("Ahmed" , 1101978733,5000);
BankAccount o3=new BankAccount("Ali",1111650924,7000);
System.out.println("Customer Name\tCustomer ID\tBalance");
o1.chkBalance();
o2.chkBalance();
o3.chkBalance();
o1.Display();
o2.Display();
o3.Display();
}
}
For a programming assignment, I am asked to write
"a) A generic constructor that takes no values. This constructor lets you use the account with all the fields set to their default values.
b) A constructor that takes five inputs. The first is a double and is the interest rate for the account, the second is a int as is the minimum balance for the account, the third is a double and is the overdraft fee for the account, the fourth is a double and is the ATM fee for the account, and the fifth is a double and is the bounced check fee for the account."
I am afraid that my code is redundant and inefficient. I was hoping someone would tell me what is unnecessary and/or if I am missing anything important. How can I create the generic constructor without manually initializing the fields? Also, I'm a bit worried that my second constructor does not initialize any fields besides the 5 listed as parameters.
public class BankAccount
{
/*Balance of BankAccount*/
private double balance = 0.00;
/*Minimum balance allowed for BankAccount*/
private int minimumBalance = 0;
/*Interest rate of BankAccount*/
private double interestRate = 0.00;
/*Fee given everytime withdrawal is made via ATM*/
private double ATMFee = 0.00;
/*Amount deducted from balance if there is an overdraft*/
private double overdraftFee = 0.00;
/*Number of withdrawals allowed to be made before fee*/
private int withdrawLimit = 0;
/*Value to be deducted from balance if withdrawal limit is exceeded*/
private double withdrawFee = 0.00;
/*Keeps track of how many withdrawals owner has made*/
private int withdrawCount = 0;
/*Fee for bouncing a check*/
private double bouncedCheckFee = 0.00;
/*Stores interest earned*/
private double interestEarned = 0.00;
/*Whether or not overdraft fee has been charged*/
private boolean overdraftFlag = false;
/*Generic constructor takes no parameters and initializes field values to their default values*/
public BankAccount()
{
this.balance = balance;
this.minimumBalance = minimumBalance;
this.interestRate = interestRate;
this.ATMFee = ATMFee;
this.overdraftFee = overdraftFee;
this.withdrawLimit = withdrawLimit;
this.withdrawFee = withdrawFee;
this.withdrawCount = withdrawCount;
this.bouncedCheckFee = bouncedCheckFee;
this.interestEarned = interestEarned;
this.overdraftFlag = overdraftFlag;
}
/*More specialized constructor takes 5 fields as parameters and initalizes them to their specified values*/
public BankAccount(double interestRate, int minimumBalance, double overdraftFee, double ATMFee, double bouncedCheckFee)
{
this();
this.interestRate = interestRate;
this.minimumBalance = minimumBalance;
this.overdraftFee = overdraftFee;
this.ATMFee = ATMFee;
this.bouncedCheckFee = bouncedCheckFee;
}
}
EDIT: Okay I edited my code according to everyone's advice.
Here it is. Is it good now?
public class BankAccount
{
/*Balance of BankAccount*/
private double balance = 0.00;
/*Minimum balance allowed for BankAccount*/
private int minimumBalance = 0;
/*Interest rate of BankAccount*/
private double interestRate = 0.00;
/*Fee given everytime withdrawal is made via ATM*/
private double ATMFee = 0.00;
/*Amount deducted from balance if there is an overdraft*/
private double overdraftFee = 0.00;
/*Number of withdrawals allowed to be made before fee*/
private int withdrawLimit = 0;
/*Value to be deducted from balance if withdrawal limit is exceeded*/
private double withdrawFee = 0.00;
/*Keeps track of how many withdrawals owner has made*/
private int withdrawCount = 0;
/*Fee for bouncing a check*/
private double bouncedCheckFee = 0.00;
/*Stores interest earned*/
private double interestEarned = 0.00;
/*Whether or not overdraft fee has been charged*/
private boolean overdraftFlag = false;
/*Generic constructor takes no parameters and initializes field values to their default values*/
public BankAccount()
{
}
/*More specialized constructor takes 5 fields as parameters and initalizes them to their specified values*/
public BankAccount(double interestRate, int minimumBalance, double overdraftFee, double ATMFee, double bouncedCheckFee)
{
this.interestRate = interestRate;
this.minimumBalance = minimumBalance;
this.overdraftFee = overdraftFee;
this.ATMFee = ATMFee;
this.bouncedCheckFee = bouncedCheckFee;
}
}
In your constructor with no arguments, you re-assign the values of your fields, which is superflous. If you already give them a value in the declaration, you don't need to do it again in the constructor if you don't want it to have a different value.
First off, your default BankAccount() constructor should be empty. It's just assigning the fields to themselves.
Second, please only include mandatory fields in your constructor. See my answer here and either use setters after creation or use the Builder Pattern to build out your object using optional parameters.
Hope this helps!
The default constructor repeat fields initialization that is already present in the field declarations. You can simply clean its body.
Another limit to your code is that when you have to create an object, you have to specify all the fields used in the constructor. You can avoid this, using the fluent interface and builder pattern to get code more readable.
Now i translate what i said in code.
The code for the BankAccountOptions class:
public class BankAccountOptions {
public static BankAccountOptions build() {
return new BankAccountOptions();
}
public double aTMFee;
public double balance;
public double bouncedCheckFee;
public double interestEarned;
public float interestRate;
public int minimumBalance;
public double overdraftFee;
public boolean overdraftFlag;
public int withdrawCount;
public double withdrawFee;
public int withdrawLimit;
public BankAccountOptions aTMFee(double value) {
aTMFee = value;
return this;
}
public BankAccountOptions balance(double value) {
balance = value;
return this;
}
public BankAccountOptions balance(int value) {
minimumBalance = value;
return this;
}
public BankAccountOptions bouncedCheckFee(double value) {
bouncedCheckFee = value;
return this;
}
public BankAccountOptions interestEarned(double value) {
interestEarned = value;
return this;
}
public BankAccountOptions interestRate(float value) {
interestRate = value;
return this;
}
public BankAccountOptions overdraftFee(double value) {
overdraftFee = value;
return this;
}
public BankAccountOptions overdraftFlag(boolean value) {
overdraftFlag = value;
return this;
}
public BankAccountOptions withdrawCount(int value) {
withdrawCount = value;
return this;
}
public BankAccountOptions withdrawFee(double value) {
withdrawFee = value;
return this;
}
public BankAccountOptions withdrawLimit(int value) {
withdrawLimit = value;
return this;
}
}
The class BankAccount
public class BankAccount {
/* Fee given everytime withdrawal is made via ATM */
private double ATMFee;
/* Balance of BankAccount */
private double balance;
/* Fee for bouncing a check */
private double bouncedCheckFee;
/* Stores interest earned */
private double interestEarned;
/* Interest rate of BankAccount */
private double interestRate;
/* Minimum balance allowed for BankAccount */
private int minimumBalance;
/* Amount deducted from balance if there is an overdraft */
private double overdraftFee;
/* Whether or not overdraft fee has been charged */
private boolean overdraftFlag;
/* Keeps track of how many withdrawals owner has made */
private int withdrawCount;
/* Value to be deducted from balance if withdrawal limit is exceeded */
private double withdrawFee;
/* Number of withdrawals allowed to be made before fee */
private int withdrawLimit;
/* Generic constructor takes no parameters and initializes field values to their default values */
public BankAccount() {
this(BankAccountOptions.build());
}
BankAccount(BankAccountOptions options)
}
/* More specialized constructor takes 5 fields as parameters and initalizes them to their specified values */
public BankAccount(BankAccountOptions options) {
balance = options.balance;
minimumBalance = options.minimumBalance;
interestRate = options.interestRate;
ATMFee = options.aTMFee;
overdraftFee = options.overdraftFee;
withdrawLimit = options.withdrawLimit;
withdrawFee = options.withdrawFee;
withdrawCount = options.withdrawCount;
bouncedCheckFee = options.bouncedCheckFee;
interestEarned = options.interestEarned;
overdraftFlag = options.overdraftFlag;
}
}
Now suppose you want to create a BankAccount object with default values. The code will be:
...
BankAccount account=new BankAccount();
...
If you want to create an account and modify only two attributes (i.e. minimumBalance and withdrawLimit) you can write:
...
BankAccount account=new BankAccount(BankAccountOptions.build().minimumBalance(200).withdrawLimit(4));
...
I have a BankAccont arraylist
public class JFrameNewAccount extends javax.swing.JFrame {
private List<BankAccount> list = new ArrayList<>();
}
and a BankAccount Class
public class BankAccount {
private String accountNo;
private String accountName;
protected double balance;
private String accountType;
public double getBalance() {
return balance;
}
}
Also, I have a button in my JFrameNewAccount that will saved the data in an arraylists.
private void btnSaveAActionPerformed(java.awt.event.ActionEvent evt) {
BankAccount account = new BankAccount();
account.setAccountName(txt_accountname.getText());
account.setAccountNo(txt_accountnumber.getText());
list.add(account);
}
I have a txt_initialbalance for balance, my problem is, how can I add the txt_initialbalance in my arraylists account.
you need to write setter and getter methods for all properties in BankAccount class...
after that your code will be as follows:
BankAccount account = new BankAccount();
account.setBalance(txt_initialbalance); //This is the setter that should be added
list.add(account);
Modify your BankAccount class to provide (possibly via the constructor) an initial balance value...
Something like...
public class BankAccount {
// Declarations...
public BankAccount(double initalBalance) {
balance = initalBalance;
}
}
Then when you want to construct a new BankAccount, you will need to parse the value from the text field...
double balance = 0;
try {
balance = Double.parseDouble(txt_initialbalance.getText());
} catch (NumberFormatException exp) {
exp.printStackTrace();
}
BankAccount account = new BankAccount(balance);
I would also suggest you take a look at How to use spinners, as it will help prevent you from running it problems with parsing the results.
You have to convert the String value of the text field to a Double value, like this:
account.setBalance(Double.valueOf(txt_initialbalance.getText());