I am at a complete loss right now. I am trying to develop a program that will display the Months, Account #, and Balance of two savings accounts and update the Balance as interest on the accounts is accrued:
For the first account 10,002 interest is accrued monthly with a yearly interest rate of 1.2%.
For the second account 10,003 interest is accrued quarterly with a yearly interest rat of 4%.
I have to design four individual classes in order to do this. SavingsAccount, SavingsAccountDriver, FlexibleSavingsAccount, and CDSavingsAccount. SavingsAccount is the parent class of both FlexibleSavingsAccount and CDSavingsAccount. SavingsAccountDriver is the Main class.
In SavingsAccount I have a method setAnnualInterestRate() that is called in SavingsAccountDriver. This method sets the interest rate for each account. The problem I am having is passing this value to the extended classes FlexibleSavingsAccount and CDSavingsAccount so that I can update the balance by adding the interest rate for each account. If anyone could please assist me on how this is done I would greatly appreciate it.
SavingsAccountDriver:
public class SavingsAccountDriver {
public static void main (String[] args) {
SavingsAccount saver1 = new SavingsAccount(10002, 2000); //create new SavingsAccount object
SavingsAccount saver2 = new SavingsAccount(10003, 3000); //create new SavingsAccount object
saver1.setAnnualInterestRate(.012); //sets AnnualInterestRate for 'saver1' object
saver2.setAnnualInterestRate(.04); //sets AnnualInterestRate for 'saver2' object
System.out.println("\nMonthly balances:\n");
System.out.println("Month " + " Account# " + " Balance " + " " + " Month " + " Account# " + " Balance ");
System.out.println("----- " + " -------- " + " ------- " + " " + " ----- " + " -------- " + " ------- ");
System.out.println(saver1.getAccountNumber() + " / " + saver1.getBalance() + " / " + saver1.getInterest());
System.out.println(saver2.getAccountNumber() + " / " + saver2.getBalance() + " / " + saver2.getInterest());
/*for(int month = 0; month <= 12; month++) {
switch(month) { // switch that outputs month, account number, and balance for both accounts (Some non-needed cases used to make output look cleaner)
case 0:
System.out.println(month + " " + saver1.getAccountNumber() + " " + saver1.getBalance() + " " + month + " " + saver2.getAccountNumber() + " " + saver2.getBalance());
break;
case 4:
saver1.addInterest();
//saver2.addInterest();
System.out.println(month + " " + saver1.getAccountNumber() + " " + saver1.getBalance() + " " + month + " " + saver2.getAccountNumber() + " " + saver2.getBalance());
break;
case 10:
saver1.addInterest();
//saver2.addInterest();
System.out.println(month + " " + saver1.getAccountNumber() + " " + saver1.getBalance() + " " + month + " " + saver2.getAccountNumber() + " " + saver2.getBalance());
break;
case 11:
saver1.addInterest();
//saver2.addInterest();
System.out.println(month + " " + saver1.getAccountNumber() + " " + saver1.getBalance() + " " + month + " " + saver2.getAccountNumber() + " " + saver2.getBalance());
break;
case 12:
saver1.addInterest();
//saver2.addInterest();
double totalBalance = saver1.getBalance() + saver2.getBalance();
System.out.println(month + " " + saver1.getAccountNumber() + " " + saver1.getBalance() + " " + month + " " + saver2.getAccountNumber() + " " + saver2.getBalance());
break;
default:
saver1.addInterest();
//saver2.addInterest();
System.out.println(month + " " + saver1.getAccountNumber() + " " + saver1.getBalance() + " " + month + " " + saver2.getAccountNumber() + " " + saver2.getBalance());
break;
}
}*/
}
}
SavingsAccount:
public class SavingsAccount {
// variables specific to SavingsAccount class
public double annualInterestRate;
private final int ACCOUNT_NUMBER;
public double balance;
//constructor with account number and balance parameters
public SavingsAccount(int account_number, double balance) {
this.ACCOUNT_NUMBER = account_number;
this.balance = balance;
}
//returns account number
public int getAccountNumber() {
return this.ACCOUNT_NUMBER;
}
//returns balance
public double getBalance() {
return this.balance;
}
//sets interest rate
public void setAnnualInterestRate (double interestRate) {
this.annualInterestRate = interestRate;
}
}
FlexibleSavingsAccount:
public class FlexibleSavingsAccount extends SavingsAccount{
public FlexibleSavingsAccount(int account_number, double balance) {
super(account_number, balance);
}
//returns interest
public double getInterest() {
return annualInterestRate;
}
}
You may want to add getInterest as an abstract method and declare SavingsAccount as abstract class. then you will have the method known by the compiler to call and you will be forced in the subclasses to provide the proper implementation
You have declared your instantiated savings accounts as type SavingsAccount. They will not have access to the method getInterest() since it is in the child class FlexibleSavingsAccount.
You need to instantiate them as the actual savings account that you wish them to actually be:
FlexibleSavingsAccount saver1 = new FlexibleSavingsAccount(10002, 2000); //create new FlexibleSavingsAccount object
Now saver1 will be able to access getInterest().
Extra idea:
What might be nicer is to code the parent SavingsAccount as an interface. You would then declare your getInterest() method in this interface, whilst leaving the details of what goes in the method to your children classes.
SavingsAccount:
public interface SavingsAccount {
public int getAccountNumber();
public double getBalance();
public void setAnnualInterestRate (double interestRate);
}
Then instantiate your accounts:
SavingsAccount saver1 = new FlexibleSavingsAccount(10002, 2000); //create new FlexibleSavingsAccount object
Note this has the added benefit that you declare your instances coded to the SavingsAccount interface which is always a nice idea for future proofing your code.
Your getInterest() method should be declared in your parent class - SavingsAccount- if you want to declare saver1 and saver2 as being of type SavingsAccount.
The way that you show, the method will only be available to classes declared as FlexibleSavingsAccount.
Since you declared them as SavingsAccount you only have access to that class' methods.
Child classes can access the methods of the parent but not the other way around.
Related
I have two methods
*`public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}`*
validateMarks(): Used to validate qualifying exam marks - qualifying marks is in the range of 65 to 100(both inclusive)
validateCourseId(): Used to validate the course entered, based on the courseId - given in the table above
calculateCourseFee(): Used to calculate the course fee after applying the discount.
So when is less than 65 print print "not elegible, you've failed" and when the course is not valid "course is not correct, please try again with the correct number of the course"
and this is my calculateCourseFee method
***if(this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else {
System.out.println("Wroog for course");
}
***
I make two different ifs for the two requirements, but everytime I run it, it prints the else statement to, even if marks is greather than 65... am I missing something?
Reviewing my code and tell me what am I missing or what am I doing wrong
The portion of the code you have shown here seems to be working as expected.
public class Driver {
public static void main(String args[]) {
Eligible e1 = new Eligible();
e1.calculateCourseFee();
}
}
class Eligible{
int qualifyingMarks = 66;
int courseId = 1002;
public boolean validateMarks() {
return (this.qualifyingMarks >= 65 && this.qualifyingMarks <= 100);
}
public boolean validateCourseId() {
return (this.courseId >= 1001 && this.courseId <= 1005);
}
public void calculateCourseFee(){
if(this.validateMarks()) {
System.out.println("works for marks");
}else {
System.out.println("wrong for marks ");
}
if(this.validateCourseId()) {
System.out.println("works for course");
}else {
System.out.println("Wroog for course");
}
}
}
output:
works for marks
works for course
Maybe the issues is with how you set the values for the qualifyingMarks and courseId variables?
I wish I could give you a like or thumbs up, I finally did it, thanks to all of your answers you gave me, and I just combined the two ifs into one. here's the code:
if(this.validateCourseId() && this.validateMarks()) {
this.courseFee = fee - (fee * discount);
System.out.println("****Course Allocation Details****" + "\n" +
"Student Name: " + this.getStudentName() + "\n" +
"Course Id: " + this.getCourseId() + "\n" +
"Qualifying Exam Marks: " + this.getQualifyingMarks() + "\n" +
"Student's Registration Id: " + this.getRegistrationId() + "\n" +
"Total Course Fee: " + this.getCourseFee() + "\n" +
"Hostel Required: " + hostel);
}else if(!this.validateCourseId()) {
System.out.println("Wrong course");
}
else if(!this.validateMarks()) {
System.out.println("You've failed");
}
Thanks everyone!!
maybe qualifyingMarks is zero or another value, print qualifyingMarks in method "validateMarks",u will get the reason of your problem.
It is meant to calculate interest and then put that into a table with years, interest, and new balance. For some reason the interest is not being calculated correctly and is not updating.
import java.util.Scanner;
import java.text.*;
public class Interest
{
public static void main(String[] args)
{
printIntro();
Scanner input = new Scanner(System.in);
System.out.print("Enter initial balance: ");
int balanceAmount = input.nextInt();
System.out.print("Enter interest rate: ");
double interestRate = input.nextDouble();
System.out.print("Enter the number of years: ");
int years = input.nextInt();
printTable(years, balanceAmount, interestRate);
}
public static double calcInterest(double balanceAmount, double interestRate, double years)
{
double interest = balanceAmount * Math.pow((1 + interestRate/100),years);
return interest;
}
public static void printRow(int rowNum, double balanceAmount, double interestRate)
{
System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
//balanceAmount = (balanceAmount + interestRate);
}
public static void printTable(int numRows, double balanceAmount, double interestRate)
{
System.out.println("Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance");
System.out.println("----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------");
for (int i = 1; i <= numRows; i++)
{
printRow(i, balanceAmount, interestRate);
balanceAmount = (balanceAmount + interestRate);
}
}
public static void printIntro()
{
System.out.println("This program will calculate the interest "
+ "earned on a deposit over a certain amount of years.");
}
}
You should call your business logic to calculate interest as per your business requirement. That totaly depend on your business requirement.
Though for program specific it seems that You need to call your calcInterest method in printTable method, before you call your printRow method as below:
public static void printTable( final int numRows, double balanceAmount, final double interestRate ) {
System.out.println( "Year" + "\t" + "Balance" + "\t" + "\t" + "Interest" + "\t" + "New Balance" );
System.out.println( "----" + "\t" + "-------" + "\t" + "\t" + "--------" + "\t" + "-----------" );
for ( int i = 1; i <= numRows; i++ ) {
double interest = calcInterest( balanceAmount, interestRate, 1 );
printRow( i, balanceAmount, interest );
balanceAmount = ( balanceAmount + interest );
}
}
Also your formula to calculate interest is wrong. it should be
double interest = balanceAmount * Math.pow( ( 1 + interestRate / 100 ), years )-balanceAmount;
It will give out put as below:
This program will calculate the interest earned on a deposit over a certain amount of years.
This program will calculate the interest earned on a deposit over a certain amount of years.
Enter initial balance: 100
Enter interest rate: 10
Enter the number of years: 3
Year Balance Interest New Balance
---- ------- -------- -----------
1 100.0 10.000000000000014 110.00000000000001
2 110.00000000000001 23.100000000000037 133.10000000000005
3 133.10000000000005 44.05610000000007 177.15610000000012
You are not calling calcInterest.
You need to call that under the printRow method before the
System.out.println(rowNum + "\t" + balanceAmount + "\t" + "\t" + interestRate + "\t" + "\t" + (balanceAmount + interestRate));
line
I'm taking a Java class and I've been working on this program that is to calculate credit card balance based on information input through a GUI. In my output Finance Charge, New Balance, and New Payment Due are all coming out as 0. I've tried adding 5 to pinpoint where I messed up and it seems that "balance" isn't being referenced correctly when calculating newBalance. I assume that Finance Charge also has the same issue but fixing balance will help me fix that as well.
//calculates balance
public float calculateBalance()
{
balance = previousBalance + currentPurchases - payments - creditsReturns + lateFees+ 5;
return balance;
}
//sets finance charge
public void setFinanceCharge(float financeCharge)
{
double periodicRate;
periodicRate = .12/12;
float d = (float)periodicRate;
financeCharge = balance * d;
}
//gets finance charge
public float getFinanceCharge()
{
return financeCharge;
}
//Method to calculate new balance
public float calculateNewBalance()
{
//calculate the new balance
newBalance = balance+financeCharge+5;
return newBalance;
}
//setes new payment due
public void setpaymentDue(double newPayment)
{
newPayment = newBalance * .10;
this.paymentDue = (float)newPayment;
}
//gets new payment due
public float getpaymentDue()
{
return paymentDue;
}
//method to display results
public void displayOutput()
{
if (overCreditLimit == 0)
{
JOptionPane.showMessageDialog(null,
"The Customer number is: " + customerNumber + "\n" +
"The Customer name is: " + customerName + "\n" +
"The Credit Limit is: " + creditLimit + "\n" +
"The Previous Balance is: " + previousBalance + "\n" +
"The Current Purchases is: " + currentPurchases + "\n" +
"The Payments is: " + payments + "\n" +
"The Credits/Returns is: " + creditsReturns + "\n" +
"The Late Fees is: " + lateFees + "\n" +
"The Finance Charge is: " + financeCharge + "\n" +
"The New Balance is: " + newBalance + "\n" +
"The New Payment Due is: " + paymentDue + "\n");
}
else
{
overCreditAmount = newBalance - creditLimit - 25;
JOptionPane.showMessageDialog(null, "You are " + overCreditAmount + " dollars over your credit limit,"
+ " a $25 fee has been charged to your new balance");
JOptionPane.showMessageDialog(null,
"The Customer number is: " + customerNumber + "\n" +
"The Customer name is: " + customerName + "\n" +
"The Credit Limit is: " + creditLimit + "\n" +
"The Previous Balance is: " + previousBalance + "\n" +
"The Current Purchases is: " + currentPurchases + "\n" +
"The Payments is: " + payments + "\n" +
"The Credits/Returns is: " + creditsReturns + "\n" +
"The Late Fees is: " + lateFees + "\n" +
"The Finance Charge is: " + financeCharge + "\n" +
"The Amount over Credit Limit is: " + overCreditAmount + "\n" +
"The New Balance is: " + newBalance + "\n" +
"The New Payment Due is: " + paymentDue + "\n");
}
}
One way I see to solve the issue is to run methods within the calculateNewMethod method. For example.
public float calculateNewBalance () {
newBalance = calculateBalance() + getFinanceCharge();
return newBalance;
}
I would also suggest avoiding code where you modify private class varibles and return them within the same method, it make more sense to have one method which modifies it, and one to return the varible.
I need the currentStockLevel for another void Method in java, is there any possibility to get it?
I think no, because of void right?
public void receive (int currentStock)
{
String outLine;
if (currentStockLevel > 0)
outLine = productCode;
{
outLine = ". Current Stock: " + currentStockLevel;
outLine += " Current Stock changed from " + currentStockLevel;
currentStockLevel += currentStock;
outLine += " to " + currentStockLevel;
int storeCost = wholeSalePrice * currentStockLevel;
System.out.println (productCode + ":" + " Received " + currentStockLevel + "." + " Store Cost " + "$" + storeCost + "." + " New stock level: " + currentStockLevel);
}
Hello fellow programmers.
Maybe it's a trivial question, yet I cant figure out solution, neither I can find any clue how to solve this. If its double post I am really sorry.
Here's the code: !! Don't forget to import your "java.util.Scanner" !!
double id[]=new double[4];
double price[]=new double[4];
String productName[]=new String[4];
id[0]=10001;
id[1]=10002;
id[2]=10003;
id[3]=10004;
price[0]=20;
price[1]=25;
price[2]=40;
price[3]=10;
productName[0]="T-Shirt";
productName[1]="More expensive T-Shirt";
productName[2]="Jacket";
productName[3]="Singlet";
int x=0;
int z=0;
int options;
double discount;
System.out.println("Type in number of your choice between 1 to 4");
Scanner menu = new Scanner(System.in);
options = menu.nextInt();
do {
System.out.println("Chosen product n.: "+ options);
}while (x > 0);
switch (options){
case 1:
System.out.println("Id of product: " + id[0] + " " + "Product price:" +price[0] + " " + "Name of product: " + productName[0]);
break;
case 2:
System.out.println("Id of product: " + id[1] + " " + "Product price: " +price[1] + " " + "Name of product: " + productName[1]);
break;
case 3:
System.out.println("Id of product: " + id[2] + " " + "Product price: " +price[2] + " " + "Name of product: " + productName[2]);
break;
case 4:
System.out.println("Id of product: " + id[3] + " " + "Product price: " +price[3] + " " + "Name of product: " + productName[3]);
break;
}
discount=idPrice(price);
System.out.println("Price after discount: " + price);
}
static double idPrice(double finalPrice[])
{
return (finalPrice[1]/0.8);
}
}
Here's the output after typing number 1:
Type in number of your choice between 1 to 4
1
Chosen product n.: 1
Id of product: 10001.0 Product price: 20.0 Name of product: T-Shirt
Price after discount: [D#3590efa8
As you can see the Price after discount is a mess. It should output number 20(25*0.8 (Hell yea 20% discount)).
That's the first question.
Next thing is. How can I spicify which finalPrice will be multiplied?
Thank you all. Hope it will be helpfull to someone else also.
You're printing an array, not it's elements.
In order to do so, you have to iterate through them:
for (double d : prices) {
System.out.println(d);
}
Edit:
After reading the comments, you should print the discount variable:
System.out.println("Price after discount: " + discount);
System.out.println("Price after discount: " + price);
Print Array of double------------------^
You need to iterate to print the price array like below
for (double d : price) {
System.out.println("Price is "+d);
}
Use java.util.Arrays.toString(price) to get a readable result.
What you are getting now is the default toString method of the Object object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}