Add balance in arraylists - java

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

Related

How to add an object to array which is an instance variable of a class in java

I have two classes named Bank and BankAccount. There is a createBankAccount method in Bank in class. I want to create an object of Bank and then add it in the record array which is a instance variable of Bank class.
class BankAccount{
double balance;
int id;
// Type of the account. Can be of two types: current or savings
String accountType;
// i. Write a Constructor
public BankAccount(double balance, int id, String accountType) {
this.balance = balance;
this.id = id;
this.accountType = accountType;
}
// ii. This function increses the balance by amount
public void deposit(double amount){
balance += amount;
}
// iii. This function decreases the balance by amount
public void withdraw(double amount){
balance -= amount;
}
}
class Bank{
BankAccount records[];
double savingInterestRate = 3.5;
double currentInterestRate = 0.4;
// iv. Write a constructor
public Bank(BankAccount[] records, double savingInterestRate, double currentInterestRate) {
this.records = records;
this.savingInterestRate = savingInterestRate;
this.currentInterestRate = currentInterestRate;
}
// v. Complete the function
public void createBankAccount(double initialBalance, int accountId, String accountType){
//Create a object of BankAccount class
// Add the object to records array
BankAccount ac = new BankAccount(initialBalance, accountId, accountType);
}
}
How do I add the BankAccount object which is created in createBankAccount method to the records array??
Is there any specific requirement to use array for records? Can't you just use a list for the same and then you can add to and remove from the list as you wish.

How can I change the variable of my Object?

I googled alot and the problem gives me a Headache because nobody can help me with it on Discord. Now I am here for help.
Thats the Class I use to make the Object
public class Main {
public static void main(String[] args) {
Konto mats = new Konto("Mats", 200);
mats.getAccount();
}
}
That is the class of it:
public class Konto extends Bankautomat{
String name;
int balance;
String prefix = "[Deutsche Bank]";
public Konto(String name, int balance){
this.name = name;
this.balance = balance;
System.out.println("New Account successfully registered!");
}
public void getAccount(){
System.out.printf("\n%s\nName: %s\nBalance: %d$\n", prefix, name, balance);
}
}
And now I want to make a Bankautomat class where I can deposit money on the Konto from "Mats"
public class Bankautomat {
public void deposit(int amount){
}
}
But I cant use mats.balance += amount
and the set or get things also dont help me
please help thank you <3
The way you have it set up, Konto extends Bankautomat right now. In other words, all Kontos are Bankautomats but the reverse is not the case. Since you only declare the field balance in the Konto class, this means it's a property of Kontos but not necessarily of all Bankautomats, so the Bankautomat object doesn't have this unless it's specifically a Konto.
To be able to access it in Bankautomat you should move the field to the Bankautomat class. Then, you'll be able to access it from both, since Konto is a Bankautomat and will inherit it. Something like this:
public class Konto extends Bankautomat{
String name;
String prefix = "[Deutsche Bank]";
public Konto(String name, int balance){
super(balance); // this calls the constructor of the superclass
this.name = name;
System.out.println("New Account successfully registered!");
}
public void getAccount(){
System.out.printf("\n%s\nName: %s\nBalance: %d$\n", this.prefix, this.name, this.balance);
}
}
and the other class:
public class Bankautomat {
int balance;
public Bankautomat(int balance) {
this.balance = balance;
}
public void deposit(int amount){
...
}
}

Using a single parameter from a Super class where the super class uses more parameters

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.

How do I create objects using more than one constructor?

I wrote the following code and driver program but I am not sure how to create bank account objects using both constructors. One constructor takes an initial balance and the second constructor opens an account with no money. Also, should the accountBalance include validity checks?
Optionally, I could do the following:
Include a fee as part of what describes a bank account. Update the BankAccount class as necessary. The user should be able to set the fee amount for each account and add the fee through a method. Add code to the driver program to demonstrate the fee functionality. (Could someone explain to me what this is asking)
//Bank Account class
import java.text.NumberFormat;
public class BankAccount {
private String ownerName;
private String accountId;
private double accountBalance;
public BankAccount(String ownerName, String accountId, double accountBalance) {
this.ownerName = ownerName;
this.accountId = accountId;
if(accountBalance >= 0) {
this.accountBalance = accountBalance;
} else {
System.out.println("Due to your negative account balace, you will be issued a fee.\n");
}
}
public BankAccount(double accountBalance) {
accountBalance = 0;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public double getAccountBalance() {
return accountBalance;
}
public void setAccountBalance(double accountBalance) {
if(accountBalance >= 0) {
this.accountBalance = accountBalance;
} else {
System.out.println("Due to your negative account balace, you will be issued a fee.\n");
}
}
public void withdraw(double amount) {
if(amount > 0 && amount < accountBalance) {
accountBalance -= amount;
} else {
System.out.println("Invalid withdraw amount! Please try again.\n");
}
}
public void deposit(double amount) {
if(amount > 0) {
accountBalance += amount;
} else {
System.out.println("Invalid deposit amount! Please try again.\n");
}
}
public String toString() {
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance();
return "Account Owner's Name: " + ownerName + "\n" + "Account ID: " + accountId + "\n" +
"Balance in the account: " + currencyFormatter.format(accountBalance);
}
}
//Driver Program
public class BankAccountDriver {
public static void main(String[] args) {
BankAccount myAccount = new BankAccount("Smith", "123jahgsd", 1200);
myAccount.withdraw(0.453);
myAccount.deposit(1000.1);
System.out.println(myAccount);
}
}
All nice answers, but they actually "miss" the "real" issue; and that is: you don't put down constructors because you can.
You create the code that is required to fulfill your requirements. In other words: you step back; and you think up respectively design the "intended use cases" for your bank account class.
And things to consider there: you avoid classes that can be created using such different paths.
Example: it is extremely dangerous to allow for empty id / owner fields. That leaves those fields with null values; and that means that you either need a lot of checking here and there; and if you forgot that here or there; you will run into NullPointerExceptions sooner or later (rather soon).
And keep in mind: your objects are meant to represent (model!) "reality". In reality, a bank account doesn't go without an owner; or an id.
In that sense, a sane implementation of your class would much more look like:
public class BankAccount {
private final String owner;
private final String id;
private double currentBalance;
public BankAccount(String owner, String id) {
this(ownwer, id, 0);
}
public BankAccount(String owner, String id, double currentBalance) {
this.owner = owner;
...
Notes here:
You want to prevent owner/id to be changed, so you make them final; and thus you also don't have setter methods for those fields
In a real world solution, you would not use Strings to represent names or ids, but distinct classes
You would also never ever use double to represent currency. This is a superbasic thing: money should not be represented using floating point numbers! (You would be looking towards to the BigDecimal class; or simply using int instead of double (and represent 1.75 $ as 175 cent)
And just a glance of real real world: nowadays, you don't model a bankaccount to have a "current balance". Instead, a bank account might be affiliated to a history of events (denoting deposits and pay-off transactions).
Final point: for your current exercise, that kind of "validation" for withdrawl/deposit is "okay"; in the "real world" validation would probably happen in many other places, too. (coming back to my initial statement: it all depends on your model; a simple model could say that a bank account itself is "validating" things; but a more realistic solution is that you have other components that deal with "rules", "laws" and all kinds of topics that do "validation").
You can do like this:
public BankAccount(String ownerName, String accountId, double accountBalance) {
this.ownerName = ownerName;
this.accountId = accountId;
this.accountBalance = accountBalance;
}
public BankAccount() {
this("some default name", "some default id", 0.0);
}
If you want to create a BankAccount with a zero balance then
public BankAccount(String ownerName, String accountId, double accountBalance) {
this.ownerName = ownerName;
this.accountId = accountId;
this.accountBalance = accountBalance;
}
public BankAccount() {
this.accountBalance = 0;
}
You can instantiate them as
BankAccount mine = new BankAccount("Scary", "123", 1000000.00);
BankAccount empty = new BankAccount();
edit
If you choose to construct a method with the second method, the id and owner would also be null and maybe not very useful
You can't create one bank account object using both constructors. You only call one of the two constructors to create a new object. So you either do:
BankAccount account = new BankAccount("Sweeper", "ABCDEF", 10000);
or:
BankAccount account = new BankAccount(100000);
Note that your second constructor's parameter is pointless because you initialize the balance to 0 no matter what the parameter is:
public BankAccount(double accountBalance) {
accountBalance = 0;
}
I think this makes more sense:
public BankAccount() {
this.accountBalance = 0;
}
As for your second question, I will give you some tips.
You need to add a new field to the class, called fee. Add getters and setters for it.
You make objects depending on which constructor you want to use. For example, to use the first constructor you need three parameters like so,
BankAccount first = new BankAccount("Bob", "ID45", 400.50);
and to use the second constructor you only need one parameter, the balance, like so,
BankAccount second = new BankAccount(400.50);
They'll both make instances of BankAccount except the difference is that on creation, the first bank account will have fields ownerName and accountId filled out while the second bank account will have those fields set to empty String values. However, the second object will have a balance of 0 unlike the first object's balance of 400.5
EDIT: Like user ScaryWombat suggested, there is a flaw in your second constructor because if you want to define an object with a balance of 0 then there's no point in adding a balance parameter. Also, in this case it would be advisable to give default values to your other fields as well,
public BankAccount() {
ownerName = "unknown";
accountId = "unknown";
accountBalance = 0;
}
So now when you create an instance of BankAccount with this constructor, it'll have the default values, "unknown", "unknown", and 0.
BankAccount third = new BankAccount();
Also, for the fee part, all you have to do is not only create another field in your BankAccount class called fee but also make a setter method to allow the user to set its fee,
private double fee;
.
.
.
public void setFee (double fee) {
this.fee = fee;
}
And in the main method, the user can access it with the following,
BankAccount account = new BankAccount("Fred", "ID145", 400);
account.setFee(15); //this will set the fee to 15

JAVA Eclipse "accessor" cannot be resolved to a variable

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)
{
...
}
....
}

Categories