I have an assignment for class and it's to go over inheritance and overloading and overriding methods. I think I did everything asked for in the instructions. However, I am a little confused about overloading and if I did it correctly. Actually not really sure how it works so I don't know if I did it all. So you do not have to read through the directions, my main question refers to, the directions that ask "Create two overloaded deposit methods in Account class such that one of them takes an integer value as the input parameter and the second one takes a double value as the input parameter." and I am not sure I did it correctly.
THANKS FOR ANY HELP!!!
Scott
Instructions available upon request.
Here is what I have....
ACCOUNT CLASS (super class)
//Account class
public class Account {
//create data fields
Scanner scan = new Scanner(System.in);
protected int id = 0;
protected double balance = 0;
protected double annualInterestRate = 0;
protected Date dateCreated;
public Account() {
dateCreated = new Date();
}
//constructor for account w/ with id and balance args.
public Account(int newID, double newBalance, double interestRate) {
dateCreated = new Date();
id = newID;
balance = newBalance;
annualInterestRate = interestRate;
}//end account method
//setter for account ID
public int setID(int newID) {
return id = newID;
}//end setID
//getter for account ID
public int getID() {
return id;
}//end getID
//setter for account balance
public void setBalance(double newBalance) {
balance = newBalance;
}//end setBalance
//getter for account balance
public double getbalance() {
return balance;
}//end method getBalance
//setter for accounts annual interest rate
public void setAnnualInterestrate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}//end setAnnualInterestRate
//getter for accounts annual interest rate
public double getAnnualInterestRate() {
return annualInterestRate;
}//end getAnnualInterestRate
//getter for date account was created
public Date getDateCreated() {
return dateCreated;
}//end getDateCreated
//calls the annual interest rate and divides by 12 to get the monthly rate
public double getMonthlyInterestRate() {
return (annualInterestRate) / 12;
}//end getMonthlyInterestRate
//method to make a withdrawal from account
public double withdraw(double withdrawAmount) {
balance -= withdrawAmount;
return withdrawAmount;
}
//two overload method to make a deposit from account
public void deposit(double depositAmount) {
balance += depositAmount;
}
public void deposit(int depositAmount) {
balance += depositAmount;
}
}
SAVINGS ACCOUNT CLASS
public class SavingAccount extends Account {
public SavingAccount(int newID, double newBalance, double interestRate) {
super(newID, newBalance, interestRate);
}
public double withdraw(double withdrawAmount){
if(balance >= withdrawAmount){
return super.withdraw(withdrawAmount);
}
else{
System.out.println("You cannot be overdraw your Savings Account! \nThe max you will be allowed to withdraw is: " + balance + "\n");
setBalance(0);
return balance;
}
}
#Override
public String toString() {
return "Account ID: " + id + "\nBalance: " + balance + "\nAnnual Interest rate: "
+ annualInterestRate + "\nDate of the Account Creation:" + dateCreated;
}
}
CHECKING ACCOUNT CLASS
public class CheckingAccount extends Account{
double overDraft = 5000;
public CheckingAccount(int newID, double newBalance, double interestRate) {
super(newID, newBalance, interestRate);
}
public double getOverdraft() {
return overDraft;
}
public void setOverdraft(double overdraft) {
overDraft = 5000;
}
public double withdraw(double withdrawAmount){
double balance = getbalance();
if(balance - withdrawAmount >= -overDraft){
return super.withdraw(withdrawAmount);
}
else{
System.out.println("reach overdraf limit!");
setBalance(-overDraft);
return overDraft + getbalance();
}
}
#Override
public String toString() {
return "Account ID: " + id + "\nBalance: " + balance + "\nAnnual Interest rate: "
+ annualInterestRate + "\nDate of the Account Creation:" + dateCreated;
}
}
TESTACCOUNT CLASS
import java.util.*;
public class TestAccount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int accID = 0;
double balance = 0;
double intRate = 0;
double withDraw = 0;
double Deposit = 0;
//savings account
System.out.println("Please enter the ID of the Savings Account: ");
accID = scan.nextInt();
scan.nextLine();
System.out.println("Please enter the initial Balance of the Savings Account: ");
balance = scan.nextDouble();
scan.nextLine();
System.out.println("Please enter the Interest Rate of the Savings Account: ");
intRate = scan.nextDouble();
scan.nextLine();
SavingAccount s = new SavingAccount(accID, balance, intRate);
System.out.println("Please enter an amount you would like to Withdraw from the Savings Account: ");
withDraw = scan.nextDouble();
s.withdraw(withDraw);
System.out.println("Please enter an amount you would like to Deposit into the Savings Account: ");
Deposit = scan.nextDouble();
s.deposit(Deposit);
System.out.println("\nSavings Account Status:\n" + s);
//Checking account
System.out.println("\nPlease enter the ID of the Checking Account: ");
accID = scan.nextInt();
scan.nextLine();
System.out.println("Please enter the initial Balance of the Checking Account: ");
balance = scan.nextDouble();
scan.nextLine();
System.out.println("Please enter the Interest Rate of the Checking Account: ");
intRate = scan.nextDouble();
scan.nextLine();
CheckingAccount c = new CheckingAccount(accID, balance, intRate);
System.out.println("Please enter an amount you would like to Withdraw from the Checking Account: ");
withDraw = scan.nextDouble();
c.withdraw(withDraw);
System.out.println("Please enter an amount you would like to Deposit into the Checking Account: ");
Deposit = scan.nextDouble();
c.deposit(Deposit);
System.out.println("\nChecking Account Status:\n" + c);
}
}
Also, is there anything else you would change to make the program better?
//two overload method to make a deposit from account
public void deposit(double depositAmount) {
balance += depositAmount;
}
public void deposit(int depositAmount) {
balance += depositAmount;
}
Yes, these are overloaded methods. You did it correctly.
Related
Every time I loop my interestRate variable is not resetting. I want it to update my interest when looping, at first I have the correct value of 1650 but when it comes to the third input all the interest from first, second, and third will just sum up. I'm expecting 1760.0 as the output but it shows 1925.0.
import java.util.*;
class SavingsAccount {
private double balance;
public static double interestRate = 0;
static double updatedrate;
public static void setInterestRate(double newRate){
interestRate = newRate;
}
public static double getInterestRate(){
return interestRate;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance=balance + amount;
}
public double withdraw(double amount){
if(balance>=amount){
balance= balance-amount;
}
else{
amount=0;
}return amount;
}
public void addInterest(){
double interest = balance * getInterestRate();
balance = balance + interest;
}
public static void showBalance(SavingsAccount account){
System.out.println("Your new Balance is "+ account.getBalance());
}
public class RunSavingsAccount {
public static void main(String[] args) {
SavingsAccount savings = new SavingsAccount();
Scanner sc = new Scanner(System.in);
try{
System.out.print("Enter Interest Rate: " );
double rate1 = sc.nextDouble();
savings.setInterestRate(rate1);
System.out.print("Enter Deposit Amount: " );
double balance1 = sc.nextDouble();
savings.deposit(balance1);
System.out.println("Your balance is: "+ balance1);
boolean bol = false;
while(!bol){
System.out.print("Press D for another deposit or W to withdraw or E to exit: ");
String transaction = sc.next();
if (transaction.equals("d")) {
System.out.print("Enter Deposit Amount: " );
double balance2 = sc.nextDouble();
savings.deposit(balance2);
savings.addInterest();
savings.showBalance(savings);
}
else if(transaction.equals("w")){
System.out.print("Enter Withdraw Amount: " );
double with = sc.nextDouble();
savings.withdraw(with);
System.out.println("");
System.out.println("Your have succesfully withdraw: "+ with);
savings.showBalance(savings);
}
else if(transaction.equals("e")){
System.out.println("Thank You Please Come Again.");
bol = !bol;
}
else{
System.out.println("Invalid Input");
}
}
}
catch(Exception e){
System.out.print("Invalid Input");
}
}
}
Output:
Enter Interest Rate: .10
Enter Deposit Amount: 500
Your balance is: 500.0
Press D for another deposit or W to withdraw or E to exit: d
Enter Deposit Amount: 1000
Your new Balance is 1650.0
Press D for another deposit or W to withdraw or E to exit: d
Enter Deposit Amount: 100
Your new Balance is 1925.0
Press D for another deposit or W to withdraw or E to exit:
You're adding interest on the whole balance after every deposit:
savings.deposit(balance2);
savings.addInterest();
Technically that would be correct if you do a deposit every year.
I'm not sure what you're trying to simulate here. Maybe you should have a separate command for adding interest only once at the end of the year or so.
if (transaction.equals("i")) {
savings.addInterest();
savings.showBalance(savings);
}
else if (transaction.equals("d")) {
System.out.print("Enter Deposit Amount: " );
double balance2 = sc.nextDouble();
savings.deposit(balance2);
savings.showBalance(savings);
}
The application does exactly what it is supposed to do.
public void deposit(double amount){
balance=balance + amount;
}
public void addInterest(){
double interest = balance * getInterestRate();
balance = balance + interest;
}
You always first add the deposit and then addInterest,so
balance: 500
addDeposit(1000) => balance 1500
addInterest => balance = 1500 + (1500 * 0,1) = 1650
addDeposit(100) => balance = 1650 + 100 = 1750
addInterest() => balance = 1750 + (1750 * 0,1) = 1750 + 175 = 1925
I guess you do not meant to have the interest on the full balance sum, or you made some other assumption which is different.
Generally, I would recommend you to get an IDE with a debugger that allows step-by-step execution of the code so you can get more insight on what is happening.
I am currently taking lessons in OOP java. In my code below i am implementing polymorphism at run time as well as inheritance. I am creating a constant named "balance".
The goal of this program is to create a class called Account and extend the class with two types of classes called SBaccount and current.
The common attributes shared with Account is name, number and amount. So far i have a working code but its not quite doing what I want yet.
I want to be able to ask the user for the type of account that needs to be created, once the user specifies the type I want to validate the user input. I also want for example if a user deposits xx amount, that amount should be added to the balance and then stored. I want in the "withdraw" method, when the user makes a withdrawal it should be taken from the balance.
My code:
import java.util.Scanner;
abstract class Account{
String number;
String name;
int amount;
static final int balance = 1000;
int bal;
public Account(){
}
int deposit(int i) {
return i;
}
void withdrawal(int i){
}
}
final class sbaccount extends Account {
public sbaccount() {
// TODO Auto-generated constructor stub
}
int deposit (int money){
bal = money + balance;
System.out.println("You have deposited :$"+money );
System.out.println("Your Account balance is now :"+bal);
return bal;
}
void withdrawal(int withdraw){
if (bal <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
amount = bal - withdraw;
System.out.println("You have withdrawn :$"+ withdraw);
System.out.println("Your Account balance is now :"+ amount);
}
}
}
final class current extends Account {
public current() {
}
int deposit ( int money){
bal = money + balance;
System.out.println("You have deposited :$"+money);
System.out.println("Your Account balance is now :"+ bal);
return bal;
}
void withdrawal(int withdraw){
if (bal <= balance){
System.out.println("Your balance is too low for withdrawal!");
}
else{
amount = bal - withdraw;
System.out.println("You have withdrawn :$"+ withdraw);
System.out.println("Your Account balance is now :"+ amount);
}
}
}
public class oopassignment {
public static void main(String[] args) {
String type;
Scanner input = new Scanner (System.in);
System.out.println("What type of account do you want to create? :");
type=input.nextLine();
Account sb;
sb = new sbaccount();
sb.deposit(500);
sb.withdrawal(100);
sb = new current();
sb.deposit(500000);
sb.withdrawal(1000000);
}
}
So you can do the following task through class.newInstance() method.
System.out.println("What type of account do you want to create? :");
String account_type = input.next();
Class c = Class.forName(account_type);
Account sb = (Account)c.getDeclaredConstructor().newInstance();
The class c will load the class according to the argument passed. And object will be created through casting (required as initially the the object is of type "Class").
So finally your code will be (some modification is done) :
import java.util.Scanner;
abstract class Account {
String number;
String name;
int amount;
static final int balance = 1000;
int bal;
abstract int deposit(int i);
abstract void withdrawal(int i);
}
final class sbaccount extends Account {
int deposit(int money) {
bal = money + balance;
System.out.println("You have deposited :$" + money);
System.out.println("Your Account balance is now :" + bal);
return bal;
}
void withdrawal(int withdraw) {
if (bal <= balance) {
System.out.println("Your balance is too low for withdrawal!");
} else {
amount = bal - withdraw;
System.out.println("You have withdrawn :$" + withdraw);
System.out.println("Your Account balance is now :" + amount);
}
}
}
final class current extends Account {
int deposit(int money) {
bal = money + balance;
System.out.println("You have deposited :$" + money);
System.out.println("Your Account balance is now :" + bal);
return bal;
}
void withdrawal(int withdraw) {
if (bal <= balance) {
System.out.println("Your balance is too low for withdrawal!");
} else {
amount = bal - withdraw;
System.out.println("You have withdrawn :$" + withdraw);
System.out.println("Your Account balance is now :" + amount);
}
}
}
public class oopassignment {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.println("What type of account do you want to create? :");
String account_type = input.next();
// The only valid optios are : sbaccount & current.
// If any other class name is inputted. It will show exception
Class c = Class.forName(account_type);
Account sb = (Account)c.getDeclaredConstructor().newInstance();
sb.deposit(500);
sb.withdrawal(100);
sb = new current();
sb.deposit(500000);
sb.withdrawal(1000000);
}
}
Let me know if any modification is needed to answer.
I am getting no errors from Eclipse but my console output is not what it should be. These are the 2 classes I am working on.
First Class
public class BankAccount
{
private double balance;
private double interestRate;
private double interest;
public BankAccount(double startBalance, double intRate)
{
balance = startBalance;
interestRate = intRate;
interest = 0.0;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount)
{
balance -= amount;
}
public void addInterest()
{
interest = balance * interestRate;
balance += interest;
}
public double getBalance()
{
return balance;
}
public double getInterest()
{
return interest;
}
}
Next Class
import java.util.Scanner;
import java.text.DecimalFormat;
public class Program2
{
public static void main(String[] args)
{
BankAccount account;
double balance = 500,
interestRate = 0.00125,
pay = 1000,
cashNeeded = 900;
Scanner keyboard = new Scanner(System.in);
DecimalFormat formatter = new DecimalFormat ("#0.00");
System.out.print("What is your account's starting balance?");
balance = keyboard.nextDouble();
System.out.print("What is your monthly interest rate?");
interestRate = keyboard.nextDouble();
account = new BankAccount(balance, interestRate);
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
System.out.println("We will deposit your pay into your account.");
account.deposit(pay);
System.out.println("Your current balance is "
+ formatter.format(account.getBalance()));
System.out.print("How much would you like to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
account.getInterest();
System.out.println("This month you have earned "
+ formatter.format( account.getInterest() )
+ " in interest.");
System.out.println("Now your balance is "
+ formatter.format( account.getBalance()));
}
}
Output which I am Getting:
What is your account's starting balance?
Output I should be getting:
What is your account's starting balance? 500
What is your monthly interest rate? 0.00125
How much were you paid this month? 1000
We will deposit your pay into your account.
Your current balance is 1500.00
How much would you like to withdraw? 900
This month you have earned 0.75 in interest.
Now your balance is 600.75
Scanners wait for input, until you give it information, it won't move on.
It is working totally fine.
I haven't modified anything in your code.
Actually I am thinking when the program is asking you to enter something, at that point you are not giving the input.
Try giving the input for example 500 when it asks What is your account's starting balance?
The program I am working on currently runs successfully but it doesn't execute part of my program and it shows no errors.
The prompt was:
"Create an application that declares a Purchase object and prompts the user for purchase details. When you prompt for an invoice number, do not let the user proceed until a number between 1000 and 8000 has been entered. When you prompt for a sale amount, do not proceed until the user has entered a non-negative number, sale amount, and sales tax. Save the file as CreatePurchase.java."
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
double tax = .05;
double totalamount;
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
while (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
}
while (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
}
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount(double totalAmount) {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
double totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
I have spent hours trying to figure out what I need to fix in order to get my display method to work. The program runs successfully, and there are no errors, so I am not sure what to even try to fix.
(Sorry if my code or question doesn't make sense.)
I would massively refactor your code if given the chance. First, the CreatePurchase class should be a simply POJO (plain old Java object), containing state for the invoice number, purchase amount, and sales tax, along with getter and setter methods for accessing and changing that state. Next, the main() method within this class will instantiate a CreatePurchase object for storing the user input. A big change I made was in how the code handles user inputs. My code below uses two while loops to poll the user for a correct invoice number (between 1000 and 8000) and amount (non negative), and only then proceeds with the remainder of the method. Finally, the CreatePurchase object created is used to output the result to the console.
public final class CreatePurchase {
private int invoiceNum;
private double amount;
private double totalamount;
// I am hard-coding the sales tax as 5%, as you did in your question,
// though this code can easily be modified if you also want to input the tax
private final double tax = .05;
public int getInvoiceNum() {
return invoiceNum;
}
public void setInvoiceNum(int invoiceNum) {
this.invoiceNum = invoiceNum;
}
public double getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double totalAmount) {
this.totalAmount = totalAmount;
}
public static void main(String[] args) {
CreatePurchase cp = new CreatePurchase();
Scanner input = new Scanner(System.in);
// these next two do-while loops will continue polling the user
// until he enters a valid input
do {
System.out.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
} while (invoiceNum < 1000 || invoiceNum > 8000);
cp.setInvoiceNum(invoiceNum);
do {
System.out.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
} while (amount < 0);
totalamount = amount*(1 + tax);
cp.setAmount(amount);
cp.setTotalAmount(totalAmount);
// now use the CreatePurchase object to print out
// details of the transaction
System.out.println("Your invoice number is:" + cp.getInvoiceNum() + ".");
System.out.println("Your sale amount is: " + cp.getAmount() + ".");
System.out.println("Your sale amount after tax is: " + cp.getTotalAmount() + ".");
}
}
You declared method public void display(int invoiceNum, double amount, double totalAmount) but you never actually used it.
try the below code, this should help!
import java.util.Scanner;
public final class CreatePurchase {
static int invoiceNum; // I made these variables static because
static double amount; // it fixed an error I was having with using
// non-static variables in a static field?
static double tax = .05;
static double totalAmount;
public void updatePurchase(final Purchase purchase) {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the invoice number! (Must be between 1000 and 8000!)");
invoiceNum = input.nextInt();
if (invoiceNum < 1000 || invoiceNum > 8000) {
System.out
.println("The invoice number you entered is invalid, try again!");
updatePurchase(purchase);
}
System.out
.println("Please enter the amount of the sale! (Must be greater than 0!)");
amount = input.nextDouble();
if (amount < 0) {
System.out.println("The sale amount is invalid, try again!");
updatePurchase(purchase);
}
setTotalAmount(tax, amount);
display(invoiceNum, amount, getTotalAmount());
}
public static void main(String[] args) {
Purchase completedPurchase = new Purchase();
new CreatePurchase().updatePurchase(completedPurchase);
}
public int getInvoiceNum(int invoiceNum) {
return invoiceNum;
}
public double getAmount(double amount) {
return amount;
}
public double getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(double tax, double amount) {
totalAmount = (amount * tax);
}
public void display(int invoiceNum, double amount, double totalAmount) {
System.out.println("Your invoice number is:" + invoiceNum + ".");
System.out.println("Your sale amount is: " + amount + ".");
System.out.println("Your sale amount after tax is: " + totalAmount
+ ".");
}
}
for the assignment, an employee has a ID number, hourly wage and works a certain # of hours. i need to calculate the gross income from those 2 values and then based of that there is withholding from the pay, in my code i believe all that is there but when i test my program i can only calculate the pay that was earned, the withholding and net pay come as a value of 0. i would appreciate any help on the issue, thank you.
// an employee has an ID, get paid an amout hourly and work an amount of hours
// tax is withheld depending on gross pay
public class Employee
{
//withholding calculation
public Employee(String empId, double hrsWrk, double hrPay)
{
employeeId = empId;
hoursWorked = hrsWrk;
hourlyPay = hrPay;
}
// access methods
public String getEmployeeId()
{
return employeeId;
}
public double getHoursWorked()
{
return hoursWorked;
}
public double getHourlyPay()
{
return hourlyPay;
}
public double getWithholding()
{
return withholding;
}
public double getIncome()
{
double income = hourlyPay * hoursWorked;
return income;
}
public double getNetPay()
{
double netPay = income - withholding;
return netPay;
}
// mutator methods
public void setId(String empId)
{
employeeId = empId;
}
public void setHoursWorked(double hrsWrk)
{
hoursWorked = hrsWrk;
}
public void setHourlyPay(double hrPay)
{
hourlyPay = hrPay;
}
//withholding calculator based on income
public void calcWithholding()
{
if(income <= 0)
{
withholding = 0.0;
}
else if(income >0 && income <= 300.0)
withholding = income*10.0/100;
else if(income >= 300.01 && income <= 400.0)
withholding = income*12/100;
else if(income >= 400.01 && income <= 500.0)
withholding = income*15/10;
else
withholding = income*20/100;
System.out.println("withholding is " + withholding);
}
public void displayWithholding()
{
calcWithholding();
System.out.println("Employee " + employeeId + " your income is " + getIncome() + " per week\n you have to pay " + getWithholding());
System.out.println("Employee " + employeeId + " your net income is " + getNetPay());
}
//instance fields
private String employeeId;
private double hoursWorked;
private double hourlyPay;
private double withholding;
private double income;
private double netPay;
}
here is the test program---------------------------------------------
import javax.swing.JOptionPane;
public class EmployeeTest
{
public static void main(String[] args)
{
String employeeId = JOptionPane.showInputDialog("Please enter your Employee ID");
String input = JOptionPane.showInputDialog("Enter your hourly wage");
double hourlyPay = Double.parseDouble(input);
input = JOptionPane.showInputDialog("How many hours have you worked this week?");
double hoursWorked = Double.parseDouble(input);
Employee richard = new Employee(employeeId, hoursWorked, hourlyPay);
richard.displayWithholding();
System.exit(0);
}
}
You're not calling getIncome until after calcWithHolding so the income variable is always zero during the calculation.
The current approach relies on side-effects from calling some of the accessors, this is generally considered to be a bad approach.
I would suggest one of the following
Ensure calculations done in the constructor (or called...)
Separate your concerns so that there is no confusion between data storage, object construction, data accessors and calculations.
Lazy initialization, so that calculated values are only calculated if they have never been accessed.