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.
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.
I completed this java project for a class, but I cannot seem to fix the error I'm getting for the web software that grades it- it's called webcat. I've tried the test input the software suggests for a reference test against my solution, and my output looks exactly the same, but I still lost points for this error-
"Error in method main of class Event: Line number 2 of your output is incorrect (line numbers begin at 1). Your main method does not print the correct output when the input is "This is a short test " (input less than 26 characters) [] Line matched except underscores: Invalid Event Code_".
How can I fix this error when the expected ouput looks fine? Thanks in advance!
Code:
public class Event {
/**
* accepts coded event info, prints the info back to std output, and
actual cost and prize number.
*
* #param args Command line arguments - not used.
*/
public static void main(String[] args) {
// variables needed
String shrink, event, date, time, section, row, seat;
double price, discount, cost;
int prizeNum;
// accept input
Scanner userInput = new Scanner(System.in);
// format the numbers
DecimalFormat formatNum = new DecimalFormat("$#,##0.00");
// enter input and trim the space
System.out.print("Enter your event code: ");
shrink = userInput.nextLine().trim();
if (shrink.length() < 26) {
System.out.println();
System.out.println("Invalid Event Code");
System.out.println("Event code must have at least 26 characters.");
return;
}
// locates spot in index of code and assigns
event = shrink.substring(25, shrink.length());
date = shrink.substring(0, 8);
time = shrink.substring(8, 12);
section = shrink.substring(19, 21);
row = shrink.substring(21, 23);
seat = shrink.substring(23, 25);
price = Double.parseDouble(shrink.substring(12, 15)
+ "." + shrink.substring(15, 17));
discount = Double.parseDouble(shrink.substring(17, 19));
// calculates final cost
cost = price - (price * (discount / 100));
// random final number
prizeNum = (int) (Math.random() * 1000 + 1);
// prints the data to std output
System.out.println();
System.out.print("Event: " + event + " " + " " + " ");
System.out.print("Date: " + date.substring(0, 2) + "/"
+ date.substring(2, 4) + "/" + date.substring(4, 8) + " "
+ " " + " ");
System.out.println("Time: " + time.substring(0, 2) + ":"
+ time.substring(2, 4) + " " + " " + " ");
System.out.print("Section: " + section + " " + " " + " ");
System.out.print("Row: " + row + " " + " " + " ");
System.out.println("Seat: " + seat);
System.out.print("Price: " + formatNum.format(price) + " " + " " + " ");
// formats discount before print
formatNum.applyPattern("#.#'%'");
System.out.print("Discount: " + formatNum.format(discount) + " "
+ " " + " ");
// formats cost before print
formatNum.applyPattern("$#,##0.00");
System.out.println("Cost: " + formatNum.format(cost));
System.out.print("Prize Number: " + prizeNum);
Output:
Enter your event code: This is a short test
Invalid Event Code
Event code must have at least 26 characters.
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.
this is probably a very basic problem but as I am only a beginner, this is confusing me. I am trying to make capitalise the first letter of a string, which I have done with the following code:
public String capitalizeFirstLetter(String product){
String productCap = product.substring(0, 1).toUpperCase() + product.substring(1);
return productCap; }
And then this capitalised version of the product just be placed in a letter writer method:
public void writeALetterChallenge(String nameFirst, String nameLast, String city, String product, String company, double retail, int numItem){
UI.println("Dear " + nameFirst);
UI.println(" You have been especially selected from the people of " + city);
UI.println("to receive a special offer for "+ product);
UI.println(productCap + " from " + company + " is a premium brand prodcut and"); UI.printf("retails for $%1.2f" + ". But, " + nameFirst + ",if you order your " + product + "\n", (retail));
UI.println("today, you can purchase it for just $" + (retail - (retail * 0.60)) + ", a saving of 60%!");
UI.println("As a special bonus, just for the " + nameLast + "family, if you order"); UI.println(numItem + " " + product + " today, you will get an additional 10% off - "); UI.println("an amazing price for " + product + " of just $" + (retail - (retail * 0.70)) + "!");
UI.println(" ");
UI.println("Hurry today and send in your order for " + product + " from " + company); UI.println("and make these fantastic savings.");
UI.println(" "); }
However my problem is that when I compile, I get the error that productCap cannot be found. So I've obviously missed something. How do I go about getting the productCap variable from the first method to be included in the second?
Any explanation on this would be great, thanks!
You should call your method:
UI.println(capitalizeFirstLetter(product) + " from " + compan ...
I think instead of this
UI.println(productCap + " from " + company + " is a premium brand prodcut and");
you want to have this
UI.println(capitalizeFirstLetter(product) + " from " + company + " is a premium brand prodcut and");
YOu can call your method as follows
UI.println(capitalizeFirstLetter(product) + " from " + company + " is a premium brand prodcut and");
Your variable productCap is local to method CapitalizaFirstLetter() and hence not accessible in another method.
To access the value of productCap, simply call CapitalizeFirstLetter() method so that it returns the value of productCap.
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());
}