//*******************************************************
// FlexibleAccount.java
//
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
//*******************************************************
import java.util.Random;
public class FlexibleAccount
{
private double balance;
private String name;
private long acctNum;
//----------------------------------------------
//Constructor -- initializes balance, owner, and account number
//----------------------------------------------
public FlexibleAccount(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}
public FlexibleAccount(double initBal, String owner, double number)
{
Random generator = new Random();
balance = initBal;
name = owner;
number=generator.nextDouble();
this.acctNum= number;
}
public FlexibleAccount(String owner)
{
balance = 0;
name=owner;
Random generator = new Random();
number=generator.nextDouble();
this.acctNum= number;
}
//----------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//----------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
}
public void withdraw(double amount,int fee)
{
if(balance>=amount)
balance-= amount+fee;
else
System.out.println("Insufficient funds");
}
//----------------------------------------------
// Adds deposit amount to balance.
//----------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//----------------------------------------------
// Returns balance.
//----------------------------------------------
public double getBalance()
{
return balance;
}
//----------------------------------------------
// Returns a string containing the name, account number, and balance.
//----------------------------------------------
public String toString()
{
return "Name: " + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
This is what i have and I'm trying to overload the FlexibleAccount 3 times as follow
public FlexibleAccount (double initBal, String owner, long number) – initializes the balance, owner, and account number as specified
public FlexibleAccount (double initBal, String owner) – initializes the balance and owner as specified; randomly generates the account number.
public FlexibleAccount (String owner) – initializes the owner as specified; sets the initial balance to 0 and randomly generates the account number.
When I compiled i get these error
FlexibleAccount.java:31: possible loss of precision
found : double
required: long
this.acctNum= number;
^
FlexibleAccount.java:39: cannot find symbol
symbol : variable number
location: class FlexibleAccount
number=generator.nextDouble();
^
FlexibleAccount.java:40: cannot find symbol
symbol : variable number
location: class FlexibleAccount
this.acctNum= number;
^
How do I fix this and is this the right way to overload?
Just like previous question - there is no such variable number when you write acctNum = number; in public FlexibleAccount(String owner):
public FlexibleAccount(String owner)
{
balance = 0;
name=owner;
Random generator = new Random();
number=generator.nextDouble(); << number is not declared
this.acctNum= number;
}
EDIT:
This is your 2nd constructor:
public FlexibleAccount(double initBal, String owner, double number)
{
Random generator = new Random();
balance = initBal;
name = owner;
number=generator.nextDouble();
this.acctNum= number;
}
For some reason you declare it with 3 arguments although you wrote you want it to be receive only 2 arguments -
public FlexibleAccount (double
initBal, String owner) – initializes
the balance and owner as specified;
randomly generates the account number.
I guess you wanted to have the variable number... it should be more something like that:
public FlexibleAccount(double initBal, String owner)
{
Random generator = new Random();
balance = initBal;
name = owner;
this.acctNum= generator.nextLong();
}
Now as you said in the prev. question this is a homework, so I won't add to that. Read the answers and comments you got until now and work it up.
Related
How do i pass a specific content of an index of an arraylist to a method? (i'm not sure of the correct terms)
This is what i'm trying to achieve:
Get user input for the amount to withdraw from the first account, then print the balance. Repeat
the same for deposit.
This is my class code:
import java.util.Date;
public class Account2 {
private int id = 0;
private double balance = 0;
private static double annualInterestRate = 0;
private Date dateCreated;
public Account2() {
id = 0;
balance = 0;
}
public Account2(int id, double balance) {
this.id = id;
this.balance = balance;
}
// getters and setters (omitted for brevity)
public double withdraw(int amount) {
return balance - amount;
}
public double deposit(int amount) {
return balance + amount;
}
}
This is the Test class:
import java.util.ArrayList;
import java.util.Scanner;
public class TestAccount2 {
public static void main(String[] args) {
//Account2 acc = new Account2();
Account2.setannualInterestRate(4.5);
//Creates an ArrayList of 3 Account objects
ArrayList<Account2> list = new ArrayList<Account2>();
for(int i=1; i<4; i++) {
//USE ARRAYLIST SYNTAX
list.add(new Account2(i+100, i*10000 ));
}
//print all the content of ArrayList
for(Account2 auto : list) {
System.out.println(temp);
}
System.out.println("Enter the amount you'd like to withdraw: ");
Scanner input = new Scanner(System.in);
double amount = amount.nextDouble;
// Get user input for the amount to withdraw from the first account, then print the balance.
// Repeat the same for deposit
}
}
This is where i'm stuck:
System.out.println("Enter the amount you'd like to withdraw: ");
Scanner input = new Scanner(System.in);
double amount = amount.nextDouble;
// Get user input for the amount to withdraw from the first account, then print the balance.
// Repeat the same for deposit
This is the method i'm trying to pass the index of arraylist into:
public double withdraw(int amount) {
return balance - amount;
}
thank u.
You need to invoke those methods specifying the instance of the account you want to alter. For example, if you want to withdraw from the first account of the ArrayList, you'll write something like:
list.get(0).withdraw(amount);
You can do the same for the deposit method.
I am trying to call a getName and getBalance method from another class called Account in my printbalances method in class bank. but it is not working it prints null after inputing customer and balance. can someone explain why and how to fix it? I can honestly say I don't know why it is not working.
Here is the class that is calling it:
class Bank {
ArrayList<Account> accounts = new ArrayList<>();
Scanner input = new Scanner(System.in);
Scanner q;
String name;
double balance;
private Account account = new Account(name, balance);
public void enterCustomers() {
System.out.println("Enter customer names or press q to quit entering names: ");
while (true) {
String name;
double balance;
System.out.print("Enter a customer name: ");
name = input.next();
if ("q".equals(name)) { //tried using == to break but wouldnt work so tried .equals since comparing strings and works
break;
}
System.out.print("Enter the opening balance : ");
balance = input.nextDouble();
accounts.add(new Account(name, balance));
}
}
public void printBalances() {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
System.out.println(account.getName() + account.getBalance());
}
and here is the classs where the get methods are stored:
class Account {
private String name;
private double balance;
public Account(String name, double balance) {
this.name = name;
this.balance = balance;
}
public String getName() {
return name;
}
//public void setName(String name) {
// this.name = name;
//}
public double getBalance() {
return balance;
}
//public void setBalance(double balance) {
// this.balance = balance;
//}
public void deposit(double amount) {
balance += amount;
}
public void withdrawal(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println(" Insufficient Balance. ");
}
}
}
The output it gives me is this:
Enter customer names or press q to quit entering names:
Enter a customer name: john
Enter the opening balance : 200
Enter a customer name: mike
Enter the opening balance : 2
Enter a customer name: q
==========================
Opening account balance
==========================
Customer Balance
==========================
null0.0
(1)deposit (2)withdraw (0)quit
I dont know why null 0.0 appears and can someone explain why?
Right now you are initializing account like this:
private Account account = new Account(name, balance);
But here name and balance are not initialized, so they are null and zero respectively by default. It looks more like you want to print the name and balance of a specific Account object, so I would pass it as an argument to printBalances:
public void printBalances(Account account) {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
System.out.println(account.getName() + " : " + account.getBalance());
}
Or if you wanted to print every balance in the accounts ArrayList:
public void printBalances() {
System.out.println("==========================");
System.out.println("Customer Balance");
System.out.println("==========================");
for(Account account : accounts) {
System.out.println(account.getName() + " : " + account.getBalance());
}
}
Are there any more references to account?
You are likely overriding it at some point because it has a name of null and a balance of 0.0
Hello I'm new to programming and a first time poster here. I'm having trouble getting a Java application to display the correct values assigned via Set methods in a public class. Specifically the CreatePurchase application returns 0 for all 3 user defined variables (invoiceNumber, saleAmount, salesTax) which are Set in the Purchase public class.
Set and display the values here
public class Purchase
{
private int invoiceNumber;
private double saleAmount;
private double salesTax;
public int getInvoiceNumber()
{
return invoiceNumber;
}
public void setInvoiceNumber(int inv)
{
inv = invoiceNumber;
}
public double getSaleAmount()
{
return saleAmount;
}
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
public double getSalesTax()
{
return salesTax;
}
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax;
}
public static void displayPurchase(Purchase aPurch)
{
System.out.println("Purchase invoice number is " + aPurch.getInvoiceNumber() + "and the sale amount is " + aPurch.getSaleAmount() + "the taxable amount is " +aPurch.getSalesTax());
}
}
This is the CreatePurchase class that prompts the user for the variables and calls the method to display the values for the new object
import java.util.Scanner;
public class CreatePurchase
{
public static void main(String args[])
{
Purchase aPurchase;
aPurchase = getPurchaseInfo();
Purchase.displayPurchase(aPurchase);
}
public static Purchase getPurchaseInfo()
{
Purchase tempPur = new Purchase();
int invoice;
double value;
double value2;
Scanner input = new Scanner(System.in);
System.out.println("Enter the invoice number:");
invoice = input.nextInt();
while(invoice < 1000 || invoice > 8000)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + invoice);
System.out.println("Please enter a whole number between 1000 and 8000");
invoice = input.nextInt();
}
tempPur.setInvoiceNumber(invoice);
System.out.println("Enter the amount of the sale:");
value = input.nextDouble();
value2 = (value * .05);
while(value < 0)
{
System.out.println("You made an invalid selection");
System.out.println("You entered " + value);
System.out.println("Please enter a non negative number");
value = input.nextDouble();
value2 = (value *.05);
}
tempPur.setSaleAmount(value);
tempPur.setSalesTax(value2);
return tempPur;
}
}
Any direction or advice on how to get the values entered to set and display properly would be greatly appreciated.
The setter needs to assign the new value to the instance field.
public void setSaleAmount(double sale)
{
sale = saleAmount;
}
Yours do the opposite now, switch the assignment around:
public void setSaleAmount(final double sale)
{
this.saleAmount = sale;
}
You can also optionally add final to the parameter (since you don't intend to change it), and make it clear what the instance field is by using this.. Purely optional, but good practice, and in this case either addition would have resulted in a compile-time error to alert you of the mistake.
Your assignments are wrong(for the setters).
It should be salesTax that is set:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
tax = salesTax; /* wrong assignment(for the purpose) */
}
And so on for your other class variables.
Remember: Setters and Getters are used to modify a class' variables.
All setters need to be modified as below:
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
//tax = salesTax; <-- This line is wrong..
this.salesTax= tax ; // Change this line and it should work...
}
public void setInvoiceNumber(int inv)
{
//inv = invoiceNumber ; --> Invalid setting
this.invoiceNumber = inv; // Correct setting
}
public void setSaleAmount(double sale)
{
//sale = saleAmount; --> Invalid setting
this.saleAmount = sale; // Correct setting
}
Reason:
tax is local variable which is specific to the method setSalesTax.
salesTax is global variable for the object.
While setting value in your object, you need to set it/assign in the global variable salesTax
To avoid confusions, The best way to use a setter would be:
Object Class:
private double amount;
public void setAmount (double amount)
{
this.amount = amount;
}
It is because you do not set the new Value to your object value.
The correct way would be
public void setSalesTax(double tax)
{
tax = saleAmount *.05;
salexTax = tax; //THIS is the mistake
}
Everytime you want to assign a value to an Object, Integer, or whatever, it goes from left to right. So, if you write:
int value=5;
int value2=10;
value2=value;
Value2 is 5 then.
Your setter method is wrong. You must use actual variable on LHS instead of formal argument.
for Ex, setInvoceNumber method should be like below :
public void setInvoiceNumber(int inv)
{
invoiceNumber = inv ;
}
Here inv is formal argument while invoiceNumber is actual variable which is going to store your value in object. You were assigning value of invoiceNumber to inv variable which has no effect in your code. Same goes for all your setter method.
public class AccountDriver {
public static void main(String[] args) {
// ID, Balance, Annual Interest Rate
Account number1 = new Account();
Account number2 = new Account(1122, 20000.00, 0.045);
// Default account
System.out.println("The Account ID is: " + number1.getId());
System.out.println("The Account Balance is: " + number1.getBalance());
// System.out.println("The Account Balance is: "+
// number1.getMontlyInterest());
System.out.println("");
// Ask to withdraw 2500
System.out.println("The Account ID is: " + number2.getId());
number2.withdraw(2500.00);
number2.deposit(3000.00);
System.out.println("Account Balance is " + number2.getBalance());
// System.out.println("The montly interest is : "+
// number2.getMontlyInterest());
System.out.println("");
}
}
public class Account {
private int id = 0;
private double balance = 0;
private double annualInterestRate = 0;
public Account(int id, double balance, double annualInterestRate) {
this.setId(id);
this.setBalance(this.balance);
this.setBalance(annualInterestRate);
}
public Account() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMontlyInterest(double montlyInterest) {
// Given Formula
// double MontlyInterest= this.balance * get.MontlyInterestRate();
return montlyInterest;
}
public double getMontlyInterestRate(double montlyInterestRate) {
// Given Formula
montlyInterestRate = this.annualInterestRate / 12;
return montlyInterestRate;
}
double withdraw(double amount) {
return balance -= amount;
}
double deposit(double amount) {
return balance += amount;
}
}
I am getting error
The Account ID is: 0
The Account Balance is: 0.0
The Account ID is: 1122
Account Balance is 20500.0
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method getMontlyInterestRate(double) in the type Account is not applicable for the arguments ()
at Account.getMontlyInterest(Account.java:41)
at AccountDriver.main(AccountDriver.java:21)
You did 2 small mistakes in your code.
In your constructor these 2 lines
this.setBalance(this.balance); // this.balance is the instance variable and not the parameter passed
^^^^ - this is not required, just use the balance parameter passed.
this.setBalance(annualInterestRate); // you are re-writing the balance with interest rate
^^^^^^^^^^ - You need to set annual interest rate and not the balance here.
should be
this.setBalance(balance); // sets the balance passed to the instance variable balance
this.setAnnualInterestRate(annualInterestRate); // sets the annual interest rate
Now since the annualInterestRate is set, you can get the monthly interest rate by modifying getMontlyInterestRate method like this.
public double getMontlyInterestRate() {
// Given Formula
return this.annualInterestRate / 12;
}
And you can print your monthly interest rate by uncommenting your System.out.println code.
System.out.println("The montly interest is : "+ number2.getMontlyInterestRate());
And the monthly interest method would look like this:
public double getMontlyInterest() { // no parameter required
// Given Formula
double MontlyInterest = this.balance * getMontlyInterestRate(); // balance multiplied by monthly interest rate
return MontlyInterest; // return the value
}
System.out.println("The montly interest is : "+ number2.getMontlyInterest());
//*******************************************************
// Account.java
//
// A bank account class with methods to deposit to, withdraw from,
// change the name on, and get a String representation
// of the account.
//*******************************************************
import java.util.Random;
public class Account
{
private double balance;
private String name;
private long acctNum;
//----------------------------------------------
//Constructor -- initializes balance, owner, and account number
//----------------------------------------------
public Account(double initBal, String owner, long number)
{
balance = initBal;
name = owner;
acctNum = number;
}
//----------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//----------------------------------------------
public void withdraw(double amount)
{
if (balance >= amount)
balance -= amount;
else
System.out.println("Insufficient funds");
}
//----------------
//Track how many accounts
//----------------
private static int numAccounts=0;
{
numAccounts++;
}
public static int getNumAccounts()
{
return numAccounts;
}
//----------------------------------------------
// Adds deposit amount to balance.
//----------------------------------------------
public void deposit(double amount)
{
balance += amount;
}
//----------------------------------------------
// Returns balance.
//----------------------------------------------
public double getBalance()
{
return balance;
}
// Get name of account
public String getName()
{
return name;
}
//----------------------------------------------
// Returns account number.
//----------------------------------------------
public long getAcctNumber()
{
return acctNum;
}
//----------------
//Void and close the accounts
//----------------
public void close()
{
balance = 0;
name += "CLOSE";
numAccounts--;
}
//----------------
//Consolidating accounts
//----------------
public static Account consolidate(Account acct1,Account acct2)
{ Account newAccount=null;
if((acct1.getName()).equals(acct2.getName()))
if(acct1.getAcctNumber()!=acct2.getAcctNumber())
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
Random generator = new Random();
acctNum= generator.nextInt();
acct1.close();
acct2.close();
}
else
System.out.println("Not allow,same account number");
else
System.out.println("Can't use other people account");
return newAccount;
}
//----------------------------------------------
// Returns a string containing the name, account number, and balance.
//----------------------------------------------
public String toString()
{
return "Name: " + name +
"\nAccount Number: " + acctNum +
"\nBalance: " + balance;
}
}
Please look at the //consolidate section. What I'm trying to do is, consolidate acct1 and acct2 into one new account, with the restrictions that is acct1 and acct2 has to has the same name, acct1 and acct2 account number has to be different from each other, and if those are met, create a new account with a new balance from the two old account, keep the same name and also randomly generate a new account number. Is there something missing in my code? It wont compile. These are errors i got
Account.java:95: ')' expected
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
^
Account.java:95: illegal start of expression
{newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner);
^
String owner should just be acct1.getName() or whatever function retrieves the name.
Also, the line acctNum = generator.nextInt(); will fail as acctNum isn't defined in that context. Furthermore, you don't set the account number of newAccount to be this acctNum variable.
I suggest you change it to this:
newAccount.setAcctNumber(generator.nextInt());
The compile error at the line
newAccount= new Account(acct1.getBalance()+acct2.getBalance(),String owner)
is because String owner is a declaration that should be used in a method signature, as you did above. When you actually make a call to the constructor, though, you need to send a String parameter in.
The compiler is complaining because what you are actually doing at this line is declaring a String variable named owner. Java won't allow that in a method call.
Finbarr is right; use the method to get the name of the account instead.