Java bank account project issue - java

So, I followed the online youtube tutorial for this, and it worked for the tutorial instructor, but not me... However, only because it wants a "getBalance" class in the source classes. If someone could help me with this, it would be greatly appreciated. I'm new to Java, and I do have some reading to catch up on in the book... So here's the program and its class setup:
BankAccountDemo.java
package bankaccountdemo;
import java.text.DecimalFormat;
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount account1 = new BankAccount(12.00);
BankAccount account2 = new BankAccount(account1);
DecimalFormat dollar = new DecimalFormat("#.##0.00");
System.out.print("The balance in account #1 is $" + dollar.format(account1.getBalance()));
System.out.print("The balance in account #2 is $" + dollar.format(account2.getBalance()));
}
}
BankAccount.java
package bankaccountdemo;
public class BankAccount {
private double balance;
public BankAccount() {
balance = 0.0;
}
public BankAccount(BankAccount obj) {
balance = obj.balance;
}
public BankAccount(double startBalance) {
balance = startBalance;
}
}
I am aware that this is a pretty simple fix, but as I said.. I have some reading to catch up on. I understood the lottery problem better than this very simple bug.

it wants a "getBalance" class in the source classes.
It doesn't want a class it wants a method that is called on your bankaccount object.
account1.getBalance()
So you need to create a method in your BankAccount class.
public double getBalance(){
return balance;
}
This function is called a getter function. In OOP languages an object's properties are usually created as private and can be modified/set and read/get using this setter and getter functions.
so you can create another function like
public void setBalance(double balance){
this.balance = balance;
}
and then you can use
account1.setBalance(10.0);
to set the amount to 10.0

As you said, you need a getBalance() method in BankAccount:
public double getBalance() {
return balance;
}

Related

javaFx application extension

i a beginner at java and I'm trying to compile 2 java codes Account.java and AccounTest.java and the command prompt keeps giving this message
"Main method not found in class Account, please define main method or a javaFX application class must extend javafx.application.Application"
researched on javafx apication and none was specific on what and where i should import. here is Account.java
"public class Account
private double balance;
public Account( double initialBalance )
{
if (initialBalance > 0.0)
balance = initialBalance;
}
public void credit( double amount)
{
balance = balance + amount;
}
public double getBalance()
{
return balance;
}
}
thanks in advance

Applying two different sets of interest rates to two objects of the same class

How can I make two objects of the same class use different interest rates?
I need to make it so that savingAccount2 and savingAccount3 use different interest rates.
savingAccount1UI savingAccount2 = new savingAccount1UI();
savingAccount1UI savingAccount3 = new savingAccount1UI();
These objects both inherit from a class called Account.java. This superclass contains all the methods that include how to calculate the interest.
Here is the current method in the superclass that calculates the 1 year interest account.java:
//add interest
public void interest(double interest){
if(balance<target){
interest = balance*lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*highRate;
balance = balance + interest;
}
updatebalance();
}
Here is the button that triggers this method:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
interest(Float.parseFloat(balanceLabel.getText().substring(1)));
Currently I am using variables with double values assigned to them, but of course this means that both objects(savingAccount2 and savingAccount3) use the same numbers. Note that these variables are stored in the Account.java superclass Like so:
public double lowRate = 0.019;
public double highRate = 0.025;
I think I may need to use a constructor for each object, with pre-set values to solve my issue but I don't understand how to implement that idea. Any suggestions?
You can write method in class Account to set the values of lowRate and highRate like:
public void setRates(double lr, double hr){
lowRate=lr;
highRate=hr;
}
Now when you create an object of class SavingsAccount, you can do:
SavingsAccount sa=new SavingsAccount();
sa.setRates(0.019,0.025);
Just do it:
savingAccount1UI savingAccount2 = new savingAccount1UI(0.019,0.025);
in class definition:
savingAccount1UI(float lowRate,float highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
when computing pass also the class to the method and access the inners value.
public void interest(double interest,savingAccount1UI account){
if(balance<target){
interest = balance*account.lowRate;
balance = balance + interest;
updatebalance();
} else{
interest=balance*account.highRate;
balance = balance + interest;
}
updatebalance();
}
It seems you are looking for this:
public class Account {
private double lowRate;
private double highRate;
//other fields
public Acount(double lowRate, double highRate) {
this.lowRate = lowRate;
this.highRate = highRate;
}
// your interest() method
// getters & setters
}
public class SavingAccount1UI extends Account {
public SavingAccount1UI(double lowRate, double highRate) {
super(lowRate, highRate);
}
// rest of your stuff
}
This way you are only able to create an object passing the values you need, like:
SavingAccount1UI savingAccount = new SavingAccount1UI(0.019, 0.025);
Now every time you call your interest() method, it will take into consideration the values passed.

Bank account class with 2 child class not showing appropriate error message

Need help with my school work, I'm very much new to programming. So the requirements are:
Class Account, change the visibility of all data to protected. Change the withdraw method so that it becomes an abstract method. This action will necessitate you declaring the class as abstract. Deposits should work the same way in OnLineAccount and SavingsAccount so make sure they cannot override their parent’s version.
The OnLineAccount class has one additional attribute to that of class Account, minimumBalance. All instances of OnLineAccount are created with the minimumBalance amount set to $500. If transactions of any OnLineAccount cause the balance to go below minimumBalance, a $25 fee is subtracted from the account balance. Override the toString method to display everything the Account toString displays plus a message dependent upon the balance. If the balance is below the minimumBalance, a message stating that a $25 fee has been already been subtracted needs to alert the customer. Use the parent class toString to do most of the work.
The SavingsAccount class has one additional attribute to that of class Account, overdraft. All instances of SavingsAccount are created with the overdraft amount set to -$1000. An overdraft amount is the amount an object of SavingsAccount class may allow the balance to go to. Implement the withdraw method so that overdrafts are allowed up to the amount stored in overdraft. Any withdrawals that allow the balance to drop below zero and up to the overdraft amount are allowed but the overdraft fee of $30 is incurred each time a transaction causes the balance to be below zero.
Override the toString method to display everything the Account toString
displays plus a message dependent upon the balance. If the balance is below zero, a message stating that the person is in overdraft and a $30 fee has been already been incurred. Use the parent class toString to do most of the work.
Create a driver class with an array of 5 objects of Account, being some instances of the child classes OnLineAccount or SavingsAccount. Systematically test the full functionality of both child classes.
================================
So I created 4 class file, it shows all account info but also showing negative balance which should be an error message instead cause balance should not be less than $500.
Here are my class files:
Account class:
import java.text.NumberFormat;
import java.util.Locale;
public abstract class Account {
private static int defaultAccountNo = 12345;
protected String owner;
protected int accountNo;
protected double balance;
protected Account(String owner, double intialDeposit){
this.owner = owner;
this.balance = intialDeposit;
defaultAccountNo++;
this.accountNo = defaultAccountNo;
}
public final boolean deposit(double amount){
if(amount<=0){
System.err.println("Negative amount can't be deposited");
return false;
}
balance = balance+amount;
return true;
}
protected abstract boolean withdrawl(double amount);
public String getBalance(){
return formatter.format(balance);
}
public int getAccountNo(){
return accountNo;
}
public void setOwner(String owner){
this.owner = owner;
}
protected void addInterest(){
double interest = 0.05*balance;
balance = balance+interest;
}
public boolean equals(Account account){
if(this.owner.equalsIgnoreCase(account.owner))
return true;
else
return false;
}
NumberFormat formatter = NumberFormat.getCurrencyInstance();
public String toString(){
return "AccountNo: "+accountNo+"\nBalance: "+formatter.format(balance);
}
}
OnlineAccount Class:
public class OnLineAccount extends Account{
public OnLineAccount(String owner, double intialDeposit) {
super(owner, intialDeposit);
}
private static final double MINIMUM_BALANCE = 500;
public boolean withdrawl(double amount){
if(amount<0){
System.err.println("Negative amount cannot be withdrawn");
return false;
}
if((balance-amount)<0){
System.err.println("Not enought balance");
return false;
}
balance = balance-amount;
if(balance<MINIMUM_BALANCE)
balance = balance - 25;
return true;
}
public String toString(){
String returnString;
if(balance<500){
returnString = super.toString()+"\n$25 fee has been already been subtracted as account balance reached below minimum";
return returnString;
}
return super.toString();
}
}
SavingsAccount Class:
public class SavingsAccount extends Account{
private static final double DEFAULT_OVERDRAFT = -1000;
public SavingsAccount(String owner, double intialDeposit) {
super(owner, intialDeposit);
}
public boolean withdrawl(double amount) {
if(amount<0){
System.err.println("Negative amount cannot be withdrawn");
return false;
}
if((balance-amount-30)<DEFAULT_OVERDRAFT){
System.err.println("Not enough balance, overdraft reached");
}
if((balance-amount)<0){
balance = balance-amount-30;
return true;
}
return false;
}
public String toString(){
String returnString;
if(balance<500){
returnString = super.toString()+"\nYour are in overdraft and $30 fee has been already been subtracted.";
return returnString;
}
return super.toString();
}
}
TestAccount Class:
import java.util.Random;
public class TestAccount {
public static void main(String[] args) {
Random ran = new Random();
Account[] accountArray = new Account[5];
Account acc1 = new OnLineAccount("Bill", 1000);
Account acc2 = new OnLineAccount("Susan", 1500);
Account acc3 = new SavingsAccount("William", 2500);
Account acc4 = new SavingsAccount("Bill", 9000);
Account acc5 = new SavingsAccount("Bruce", 1355);
accountArray[0] = acc1;
accountArray[1] = acc2;
accountArray[2] = acc3;
accountArray[3] = acc4;
accountArray[4] = acc5;
for(int i=0; i<accountArray.length; i++){
System.out.println("Initial details of Account....");
System.out.println(accountArray[i]);
System.out.println("After some transactions..");
accountArray[i].deposit(ran.nextInt(300));
accountArray[i].withdrawl(ran.nextInt(3000
));
System.out.println("Balance: "+accountArray[i].getBalance());
System.out.println("After adding the interest for the year....");
accountArray[i].addInterest();
System.out.println("Balance: "+accountArray[i].getBalance());
System.out.println(); // for blank line
}
System.out.println("Checking for Duplicates now....");
for(int i=0; i<accountArray.length; i++){
for(int j=0; j<i; j++){
if(accountArray[i].equals(accountArray[j])){
System.out.println("Account "+accountArray[i].getAccountNo()+
" and "+accountArray[j].getAccountNo()+" are duplicates");
}
}
}
}
}
I spent hours with no luck. Any help would be much appreciated. Thanks.
This is my first post here.
The output I'm getting is (Account no 12350 is getting negative balance...):
Negative amounts are possibile in your code.
Imagine this scenario with an online account.
Robert has 3000 dollars. He withdraws 2990 dollars. There are only 10 dollars remaing.
Seeing that 10 dollars is less than the minimum amount, you subract 25 dollars.
So Robert will have -15 dollars on his account.
Thanks guys for your help. It's now working perfectly with all error messages showing up. I added toString() after getBalance() as J Richard Snape suggested and all OK now.
As Richard said, getBalance() was bypassing all warning.
Output now:
Negative amounts are possible because you have a bound that is higher than some of the person's initial amount deposited.
With the deposit and withdrawal in your block of code, you can withdraw into an amount that causes the person to have a balance in the negative.
accountArray[i].withdrawl(ran.nextInt(3000
));

Need explanation of java Class collaboration/aggregation

I'm working on an assignment where I need to make 3 classes for a car simulator. One for the fuel and one for the mileage. "The mileage class should be able to work with a FuelGauge object. It should decrease the FuelGauge object's current amount of fuel by 1 gallon for every 24 miles traveled. (The car's fuel economy is 24 miles per gallon)." I'm just really struggling on understanding how to properly link the classes together so that they can do what is necessary.
A good explanation from someone would be greatly appreciated.
I hope I understand your problem correctly.
Simple answer is that FuelGauge class will have attribute amount, which will be accessible through simple setter/getter.
public class FuelGague {
private double amount;
// Starting amount of fuel
public FuelGague(double amount) {
this.amount = amount;
}
// Not sure if you really need this method for your solution. This is classic setter method.
public void setAmount(double amount) {
this.amount = amount;
}
public double getAmount() {
return amount;
}
// I guess this is what do you actually want to do
public void changeAmount(double difference) {
amount += difference;
}
}
public class Mileage {
private FuelGague fuelGague;
public Mileage(FuelGague fuelGague) {
this.fuelGague = fuelGague;
}
// This will be main method where you can decrease amount for guelGague
public void methodForMileage() {
fuelGague.changeAmount(-1);
}
public FuelGague getFuelGague() {
return fuelGague;
}
public void setFuelGague(FuelGague fuelGague) {
this.fuelGague = fuelGague;
}
public static void main(String[] args)
{
FuelGague fuelGague= new FuelGague(50);
Mileage mil = new Mileage(fuelGague);
}
}
As you can see Mileage class has refference to fuelGague object which is passed in constructor and it can be manipulated by public method of FuelGague class. I added set method for Mileage class so you can even set different FuelGague class object.

Java import giving error

Again, I am a java n00b and I am trying to learn from scratch and running into some embarrassing problems.
I got an Account class as follows:Account.java
public class Account
{
protected double balance;
// Constructor to initialize balance
public Account( double amount )
{
balance = amount;
}
// Overloaded constructor for empty balance
public Account()
{
balance = 0.0;
}
public void deposit( double amount )
{
balance += amount;
}
public double withdraw( double amount )
{
// See if amount can be withdrawn
if (balance >= amount)
{
balance -= amount;
return amount;
}
else
// Withdrawal not allowed
return 0.0;
}
public double getbalance()
{
return balance;
}
}
I am trying to use extends to inherit the methods and variables in this class. So, I used InterestBearingAccount.java
import Account;
class InterestBearingAccount extends Account
{
// Default interest rate of 7.95 percent (const)
private static double default_interest = 7.95;
// Current interest rate
private double interest_rate;
// Overloaded constructor accepting balance and an interest rate
public InterestBearingAccount( double amount, double interest)
{
balance = amount;
interest_rate = interest;
}
// Overloaded constructor accepting balance with a default interest rate
public InterestBearingAccount( double amount )
{
balance = amount;
interest_rate = default_interest;
}
// Overloaded constructor with empty balance and a default interest rate
public InterestBearingAccount()
{
balance = 0.0;
interest_rate = default_interest;
}
public void add_monthly_interest()
{
// Add interest to our account
balance = balance +
(balance * interest_rate / 100) / 12;
}
}
I get an error saying import error '.' expected when I try to compile. All the files are in the same folder.
I did javac -cp . InterestBearingAccount
If all the files are in the same folder / package, you don't need to do an import.
When you define your class you can optionally include a package statement at the top of the file. This mandates the package that the class belongs to and should correlate to its position on the file system. For example, a public class Account in package com.foo should be defined in the following file hierarchy:
com
|
|--foo
|
|--Account.java
As you have omitted the package statement both your classes belong to the anonymous package. For classes belonging to the same package there is no need to import classes in order to reference them; this is only a requirement for classes in a different package.
if you're classes are in the same package, it's not necessary to import. Otherwise you should import the package + the Class name.
make InterestBearingAccount class public, like
public class InterestBearingAccount {}

Categories