Iterator loop with array - java

I just have what I'm sure is a very easy and quick question here... So let's say I have an Account class as follows:
import java.text.NumberFormat;
public class Account
{
private final double RATE = 0.03; // interest rate of 3.5%
private long acctNumber;
private double balance;
private String name;
//-----------------------------------------------------------------
// Sets up the account by defining its owner, account number,
// and initial balance.
//-----------------------------------------------------------------
public Account (String owner, long account, double initial)
{
name = owner;
acctNumber = account;
balance = initial;
}
//-----------------------------------------------------------------
// Deposits the specified amount into the account. Returns the
// new balance.
//-----------------------------------------------------------------
public double deposit (double amount)
{
balance = balance + amount;
return balance;
}
//-----------------------------------------------------------------
// Withdraws the specified amount from the account and applies
// the fee. Returns the new balance.
//-----------------------------------------------------------------
public double withdraw (double amount, double fee)
{
balance = balance - amount - fee;
return balance;
}
//-----------------------------------------------------------------
// Adds interest to the account and returns the new balance.
//-----------------------------------------------------------------
public double addInterest ()
{
balance += (balance * RATE);
return balance;
}
//-----------------------------------------------------------------
// Returns the current balance of the account.
//-----------------------------------------------------------------
public double getBalance ()
{
return balance;
}
//-----------------------------------------------------------------
// Returns a one-line description of the account as a string.
//-----------------------------------------------------------------
public String toString ()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return acctNumber + "\t" + name + "\t" + fmt.format(balance);
}
}
And I create the Bank class shown here...
public class Bank
{
Account[] accounts;// = new Account[30];
int count=0;
String name;
public Bank(String name)
{
this.name = name;
accounts = new Account[30];
}
public void addAccount(Account acct)
{
accounts[count] = acct;
count++;
}
public void addInterest()
{
//for (Account acct : accounts)
//acct.addInterest();
for(int i = 0; i < count; i++)
accounts[i].addInterest();
}
}
I receive an error if I try to use the addInterest() method with the
for (Account acct: accounts) loop you see commented out. Can someone please provide me with insight on why this is? I thought these loops were equivalent. Thanks in advance.

The for loop over an iterable array iterates all 30 elements, not only the elements you really added.
You may use an ArrayList<Account> and add elements as needed. This allows you to omit the count field:
public class Bank
{
ArrayList<Account> accounts = new ArrayList<Account>();
String name;
public Bank(String name)
{
this.name = name;
}
public void addAccount(Account acct)
{
accounts.add(acct);
}
public void addInterest()
{
for (Account acct : accounts)
acct.addInterest();
}
}

You have to initialize the Account array
so you might want to change this to:
public void addInterest()
{
//for (Account acct : accounts)
//acct.addInterest();
for(int i = 0; i < count; i++)
accounts[i].addInterest();
}
to something like this:
public void addInterest()
{
for (Account acct : accounts) {
acct= new Account("John",1234596069,200.00);
acct.addInterest();
}
// for(int i = 0; i < count; i++)
// accounts[i].addInterest();
}
Essentially you have to initialize the array variable before invoking a method.

Related

The method is no applicable to the arguments in Java

I am fairly new to objects and classes in Java, so sorry for the newbie question. In the main method's print statement I get the error:
The method getId(int) in the type Account is not applicable for the arguments ()
I am not quite sure what exactly is happening here, but I am just trying to print user2's id. Thank you in advance.
I also do apologize for trying to get all the code into a single block, but I had some issues, clearly.
package problems;
import java.time.LocalDate;
public class AccountTest {
public static void main(String[] args) {
//User 1 with no input values
Account user1 = new Account();
//User 2 with the specified id and balance values
Account user2 = new Account(1122, 20000);
//Test to see if the getters and setters work
System.out.println("The id is + " + user2.getId());
}
}
//Create the class
class Account {
private int id;
private double balance;
private static double annualInterestRate;
private LocalDate dateCreated;
//Object for when no values are passed
Account() {
id = 0;
balance = 0;
annualInterestRate = 4.5;
System.out.println("There are no parameters set for the object");
}
//Object for when values are passed
Account(int id, int balance) {
this.id = id;
this.balance = balance;
annualInterestRate = 4.5;
dateCreated = LocalDate.now();
}
//Getters
public int getId(int id) {
return this.id;
}
public double getBalance(double balance) {
return this.balance;
}
public double getMonthlyInterest(double annualInterestRate) {
return (annualInterestRate / 100 /12 * balance);
}
//Setters
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
//Deposit and withdraw methods
public double withdraw(double balance) {
this.balance = balance - 2500;
return this.balance;
}
public double deposit(double balance) {
this.balance = balance + 3000;
return this.balance;
}
//Get the date for when the account was made
public long getDate(long dateCreated) {
return dateCreated;
}
}
As the name implies, when you do a getter, you get a value, so there is no point in giving it an argument when all it does is return the value of the private variable.
Example:
private String myVar;
public String getMyVar()
{
return this.myVar;
}
public void setMyVar(String theValueIWantMyVar)
{
this.myVar = theValueIWantMyVar;
}
I recommend you read a little to see how object oriented programming works
https://dev.to/codegym_cc/18-best-java-books-for-beginners-in-2019-fme

Reading a file and writing to cmd window using mutators/accessors

I'm working on a project for school and seem to have dug myself into a rabbit hole. I need to read a file consisting of just positive and negative numbers from a file and display them to a command window along with the date. I was able to get the end result but cannot list the marginal results. Thanks in advance!
class Account{
private int id = 0; //private int data field named id for the account (default 0).
private double balance = 0.0; //private double data field named balance for the account (default 0)
private static double annualInterestRate = 0.0; //private double data field named annualInterestRate that stores the current interest rate (default 0). Assume all accounts have the same interest rate.
private java.util.Date dateCreated; //private Date data field named dateCreated that stores the date when the account was created.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public Account() { //no-arg constructor that creates a default account.
dateCreated = new java.util.Date();
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public Account(int id, double balance) { //constructor that creates an account with the specified id and initial balance.
this();
this.id = id;
this.balance = balance;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public int getId() {//accessor and mutator methods for id, balance, and annualInterestRate.
return this.id;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public double getBalance() {//accessor and mutator methods for id, balance, and annualInterestRate.
return this.balance;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public double getAnnualInterestRate() {//accessor and mutator methods for id, balance, and annualInterestRate.
return annualInterestRate;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public String getDateCreated() {//accessor method for dateCreated
return this.dateCreated.toString();
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public void setId(int id) { //mutator for id
this.id = id;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public void setBalance(double balance) { //mutator for balance
this.balance = balance;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public void setAnnualInterestRate(double annualInterestRate) { //mutator annual interest rate
this.annualInterestRate = annualInterestRate;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public double getMonthlyInterestRate() { //method named getMonthlyInterestRate() that returns the monthly interest rate.
return (annualInterestRate / 100) / 12 ;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public double getMonthlyInterest() { //method named getMonthlyInterest() that returns the monthly interest.
return balance * getMonthlyInterestRate();
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public void withdraw(double amount) { //method named withdraw that withdraws a specified amount from the account.
this.balance -= amount;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
public void deposit(double amount) { //method named deposit that deposits a specified amount to the account.
this.balance += amount;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
}//end class account
I'm pretty sure that class is OK. It's the one with the main method that I need the most help or guidance with.
import java.util.Scanner;
import java.io.*;
public class AccountHomework{
public static void main(String[] args)throws IOException{
File fn = new File("transactions.txt");
Scanner dataIn = new Scanner(fn);
Account account = new Account(1122, 20000);
double[] transactions = new double[10];
account.setAnnualInterestRate(4.5);
account.withdraw(2500.0);
account.deposit(3000.0);
printMethod(account);
}
public static void printMethod(Account acct){
System.out.printf(" %8s %17s %13s","Balance","Monthly Interest","Date Created\n");
System.out.printf(" $%6.2f $%6.2f %s\n",acct.getBalance(),acct.getMonthlyInterest(),acct.getDateCreated());
}
public static void fillTransactions(Scanner dataIn, Stock[] stocks){
double transactions;
for(int indx = 0; indx<stocks.length;indx++){
transactions = dataIn.nextDouble();
dataIn.nextLine(); // read the extra carriage return
if (transactions < 0)
dataIn.withdraw();
else
dataIn.deposit();
account[indx] = new Account();
account[indx].populateStockData(transactions);
}//end for
}//end fillStockArray
}
I noticed 2 things:
1. the scanner dataIn is not used to read the data, I see you have a method fillTransaction, but its not called from main
2. Within fillTransactions you are using the methods withdraw() and deposit() on the scanner, when the methods are actually defined on the class Account

resolving bracketing error when creating constructors in Java

I am getting a bracketing error in Eclipse (lines 15 & 18) "public Account myCustomAccount ... balance = initial balance; }" when I try to open my second constructor in the following program. The program is for Dietel "Introduction to Programming" chapter 9 exercise 7.
I suspect that I am creating the constructor incorrectly. What advice do you offer? (Thank you kindly in advance!!)
import java.util.Date;
public class Account {
//declare required variables
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0; //assume all accounts have the same interest rate
private Date dateCreated = new Date(); //no-argument instance stores the present date
//define default & custom constructors
public Account mydefaultaccount = new Account(); //no-argument instance of Account
public Account myCustomAccount = new Account(int identNum, double initialBalance) {
id = identNum;
balance = initialBalance;
}
//define getters
public int getId() {
return id;
}
public double getBalance() {
return balance;
}
public double annualInterestRate() {
return annualInterestRate;
}
public Date getDate() {
return dateCreated;
}
//define setters
public void setId(int idSetter) {
id = idSetter;
}
public void setBalance(double balanceSetter) {
balance = balanceSetter;
}
public void setAnnualInterestRate(double annualSetter) {
annualInterestRate = annualSetter;
}
//define required monthly interest rate getter
public double getMonthlyInterestRate() {
double moInt = annualInterestRate / 12;
return moInt;
}
//define modifiers
public double withdraw(int withdraw) {
balance = balance - withdraw;
}
public double deposit(int deposit) {
balance = balance + deposit;
}
}
That isn't how you define constructors. Constructors should follow the form:
public className(parameters) {}
Then, to instantiate the class, call this:
ClassName variable = new ClassName(Parameters);
In your case,
public Account() {
/* Body */
}
public Account(int identNum, double initialBalance) {
/* Body */
}
And to instantiate,
Account ac = new Account(Parameters);

Get specific element from ArrayList

In main I do this:
First I create a new customer with its first name, lastname and number.
Then I create two savingsAccounts, with its amount, id and interest rate.
I then add the two savingsAccounts to the new customer.
Finally I add the new customer to the bank.
Customer newCustomer = new Customer(firstName, lastName, pnumber);
SavingsAccount savingsAccount1 = new SavingsAccount(400, "1", 4); //400$ into account no.1, with interest 4%
SavingsAccount savingsAccount2 = new SavingsAccount(300, "2", 3);
newCustomer.addAccount(savingsAccount1);
newCustomer.addAccount(savingsAccount2);
bank.addCustomer(newCustomer);
Here is class Bank:
public class Bank {
String bankName;
private ArrayList<Customer> customers = new ArrayList<Customer>();
Bank(String bankName) {
this.bankName = bankName;
}
public void addCustomer(Customer newCustomer) {
customers.add(newCustomer);
}
}
Here is class Customer:
public class Customer {
private String firstName;
private String lastName;
private String number;
private ArrayList<Account> accounts;
Customer(String firstName, String lastName, String number) {
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
this.accounts = new ArrayList<Account>();
}
public void addAccount(SavingsAccount account) {
accounts.add(account);
}
public void addAccount(CreditAccount account) {
accounts.add(account);
}
public ArrayList<Account> getAccounts() {
return accounts;
}
}
Here is class SavingsAccount (that inherits class Account):
public class SavingsAccount extends Account {
public SavingsAccount() {
super();
}
public SavingsAccount(double bal, String id, double inte) {
super(bal, id, inte);
}
#Override
public void deposit(String number, String id, double amount) {
}
#Override
public void withdraw(String number, String id, double amount) {
}
#Override
public void transfer(String number, String id, double amount) {
}
#Override
public double getBalance() {
}
#Override
public String getAccountId() {
return accountId;
}
#Override
public double getInterest(){
return interest;
}
}
My problem is:
How can I write code in class SavingsAccount to deposit, withdraw, transfer money for a certain customer, for a certain account?
Let's say I want to deposit 500 to customer no.2 on his account no.1.
That should be something like savingsAccount.deposit("2", "1", 500);
I just can't figure out how to access customer number 2, and his account number 1.
Can anyone help me please?
What you could do is have a method for that in the Bank class:
public class Bank {
// Your stuff
// new method:
public boolean transfer(Account accountFrom, double amount, String nameTo, int account) {
//check if the balance can be deposit from the account
if(amount <= accountFrom.getBalance()) {
//Check if the person exists in the bank
String name = nameTo.split(" "); // name[0] is the first name, name[1] last name
boolean success = false;
for(Customer c: customers) {
if(c.getFirstName().equalsIgnoreCase(name[0]) &&
c.getLastName().equalsIgnoreCase(name[1]) {
for(Account a : c.getAccounts()) {
if(a.getAccountId() == account) {
// Add it to the account
a.deposit(amount);
success = true;
break;
}
}
break;
}
}
// Deposit it from the account (That class should only keep track of money, so it
// only takes an argument to deposit or withdraw a value, the rest is done by the bank
// Only do this if money has been dsposited at the target account
if(success){
accountFrom.withdraw(amount);
return true;
}
}
return false;
}
}
For this to happen you have to structurely change your setup.
Have the accounts only manage money, those accounts get added to a customer. The customer is the person who communicates between the bank and himself. And finally the bank communicates with customers.
I hope this will help you in the direction

Initializing array of objects to $100

This program creates 10 accounts and sets the balance to $100 each.
I wrote a for loop to initialize the balance but doesn't work.
The setBalance() method is not recognize within the AccountArray Class
How do I assign $100 balance to each account?
public class AccountArray{
public static AccountArray[] createAccountArray(){
AccountArray[] atm = new AccountArray [10];
for(int i = 0; i < atm.length; i++){
atm[i] = new AccountArray(setBalance(100));
}
return atm;
}
}
import java.util.Date;
public class Account{
public int id = 0;
public double balance = 0;
public double annualInterestRate = 0;
public double withdraw;
public double deposit;
java.util.Date date = new java.util.Date();
public Account(){
}
public Account(int id, double balance, double annualInterestRate){
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
}
public Account(int id, double balance, double annualInterestRate, Date date){
this.id = id;
this.balance = balance;
this.annualInterestRate = annualInterestRate;
this.date = date;
}
public void setID(int id){
this.id = id;
}
public int getID(){
return id;
}
public double getBalance(){
return balance - withdraw + deposit;
}
public void setAnnualInterestRate(double annualInterestRate){
this.annualInterestRate = annualInterestRate;
}
public double getAnnualInterestRate(){
return (annualInterestRate/100);
}
public Date getDateCreated(){
return date;
}
public double getMonthlyInterestRate(){
return getBalance() * ((annualInterestRate/100) / 12);
}
public void withdraw(double withdraw){
this.withdraw = withdraw;
}
public double deposit(){
return balance + deposit;
}
public void deposit (double deposit){
this.deposit = deposit;
}
}
.
public class TestAccount extends AccountArray{
public static void main(String[] args) {
Account account1122 = new Account(1122, 20000, 4.5);
account1122.withdraw(2500);
account1122.deposit(3000);
System.out.println("Your account balance is: \t" + "$"+ account1122.getBalance() +
"\nYour monthly interest rate is: \t" + "$" + account1122.getMonthlyInterestRate() +
"\nYour account was created on: \t" + account1122.getDateCreated());
//Declare account array */
AccountArray[] atm;
//Create Account array */
atm = createAccountArray();
System.out.println(atm[i].getBalance);
}
}
Your program is attempting to create 10 AccountArray instances, not 10 Accounts. Even if that were to work, you're calling a method outside of the context of either a static reference or the object instance - that is never going to work.
What you probably want to do is this:
Account[] atm = new Account[10];
for(int i = 0; i < atm.length; i++){
atm[i] = new Account();
atm[i].setBalance(100);
}
...although ignoring the other constructors in this case seems a bit...wrong to me. I leave this part as an exercise for the reader.

Categories

Resources