Write a class for a simple credit card account - java

A credit account has a description, principal balance, an APR, a minimum monthly payment percentage (usually between 1% and 3%) and a minimum monthly payment amount.In addition to the constructor, setters, getters, and toString methods, add methods to make a purchase using the credit card (increasing the principal by a certain amount), make a payment on the card (decrease the principle by a certain amount), calculate the monthly interest amount (principal balance * APR/12), and calculate the minimum monthly payment (principal balance * minimum monthly payment rate or the minimum monthly payment amount, whichever is greater, or the principle balance if it is lower than the calculated minimum payment amount). Hint: If storing the rates as percentages, remember to divide by 100 to get the decimal value (ex. 2% means to multiply by .02).
Since most people have multiple credit cards, use this class to write an application to maintain a list of credit cards (create an array of credit card objects), and present the user with the principal, interest, and minimum payment amount for the month for each card in the list.
Add a method to the credit card class to calculate the number of months it would take to pay off the card (get to a balance of zero) if only the minimum monthly payment was paid each month. Remember that this method should not change the current information for the card in any way, it is just a calculation.
This is what I have so far:
public class CreditCardDebt {
//Instance Variables
private String cardName;
private double princBal;
private double aPR;
private double monthPayPercent;
private double monthPayAmount;
//Constructor
public CreditCardDebt(String name, double origBal, double apr, double mnthPercent, double mnthAmount) {
cardName = name;
princBal = origBal;
aPR = apr;
monthPayPercent = mnthPercent;
monthPayAmount = mnthAmount;
}
//Mutator/Setter
public void cardName(String name){
cardName = name;
}
public void princBal(double origBal){
princBal = origBal;
}
public void aPR(double apr){
aPR = apr;
}
public void monthPayPercent(double mnthPercent){
monthPayPercent = mnthPercent;
}
public void monthPayAmount(double mnthAmount){
monthPayAmount = mnthAmount;
}
//Accessor/Getter
public String getCardName () {
return cardName;
}
public double getPrincBal () {
return princBal;
}
public double getAPR () {
return aPR;
}
public double getMonthPayPercent () {
return monthPayPercent;
}
public double getMonthPayAmount () {
return monthPayAmount;
}
//Other Methods
public double addPurchase () {
return princBal+;
}
public double makePay () {
return -princBal;
}
public double calcMonthInterestAmnt () {
return princBal*(aPR/12);
}
public doublt calcMinMonthPay () {
return princBal *
//toString
public String toString () {
return "Card: " + cardName + " has a principle balance of: "
+ princBal + ", an APR of " + aPR +
", a minimum monthly payment percentage of " + monthPayPercent +
", and a minimum monthly payment amount of " + monthPayAmount + ".";
}
}
I know I'm missing a lot.. Please help.

The description you have given is basically check-list of functionality that needs to be implemented.
My suggestion is to break each task down into smaller and smaller bits and that you can work your way through and check of as you do them. This will give you a nice roadmap, and also give you good feels as you check of each task, which will provide you with much needed encouragement.
If a task is too much, try to break it down into smaller tasks that you can easily check off.
The description is pretty much already in the order that the code needs to be written in, so just work your way through the list.
If you run into a specific problem that you are struggling to solve, post a new question on Stack Overflow that follows the How to ask a good question guide
Here is the description broken up into separate reasonably manageable tasks:
Create a credit account class that has the following properties:
a description
principal balance,
an APR
a minimum monthly payment percentage (usually between 1% and 3%)
a minimum monthly payment amount
Has a constructor
Set each property to their initial values
Has getters and setters for each property
Has a toString method
Has a method to make a purchase
increases the principal by a certain amount
Has a method to make a payment
decrease the principle by a certain amount
Has a method to calculate the monthly interest amount
principal balance * APR/12
Has a method to calculate the minimum monthly payment
principal balance * minimum monthly payment rate or, the minimum monthly payment amount, whichever is greater or the principle balance if it is lower than the calculated minimum payment amount
Hint: If storing the rates as percentages, remember to divide by 100 to get the decimal value (ex. 2% means to multiply by .02).
Create an application that maintain a list of credit cards
create an array of credit card objects
for each card in the list
present the user with the principal, interest, and minimum payment amount for the month.
Add a method to the credit card class to calculate the number of months it would take to pay off the card
if only the minimum monthly payment was paid each month.
Remember that this method should not change the current information for the card in any way, it is just a calculation.

Related

Looking to get the yearly returns on this total compound interest calculator

I'm really new to Java so please excuse if this isn't the 100% right way to even write this code.
So I've been messing around with this code for about 6 hours now, and I can not for the life of me figure out how to fix this issue:
I have a compound interest calculator that takes user input for the variables of term length, initial amount, and APR. I can get the answer I want if it was just the simple one time calculation, but I really want it to show me the amount increased each year of a term. For example:
If the interest is calculated for 10 years, I want it to show me the amount for each year leading up to it. Right now all I get is a static number of 1, or infinity.
How do I get this program to show me the total amount for the term (i.e. the length of the user input investment), broken down per year with the amount shown per year?
The code is:
import java.util.Scanner;
import java.lang.Math;
public class CompoundInterestCalculator {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
double initial; // the intial amount your loan is set for
int term; // the number of years you want to calculate
float yearlyrate; // interest rate
int repeat;
// System message to alert users to program use
System.out.printf("Hi there! I can calculate compound interest for you at a fixed interest
rate and term.\n\nPlease enter numbers without commas or symbols to get an accurate result!");
// Prompt for initial investment amount
System.out.println("\nPlease enter your initial investment.");
// Store value of user input for initial investment
initial = scan.nextDouble();
// Prompt for interest percentage
System.out.println();
System.out.println("Please enter the annual interest percentage.");
System.out.println();
// Store value of user input for interest amount
yearlyrate = scan.nextFloat();
// Prompt for length of the term for investment
System.out.println();
System.out.println("Please enter the length of your investment in years.");
// Store Value of user input for term length
term = scan.nextInt();
//For loop to set up calulations, repeats, and totals
for(repeat = 0; repeat < term; repeat++) {
System.out.println();
System.out.println("Your investment amount after" + (repeat+1) + "years is:");
// calculation for determining compound interest at a yearly rate and over the term
double total = Math.pow(initial * (1 + (yearlyrate/100) / 12) , 12/term);
// Displays the total value to the user
System.out.println("$" + total);
// Seperation line to clean it up
System.out.println();
// Close the scanner
scan.close();
}
}
}
Any help would be greatly appreciated because I am really out of my depth with this one.
Just a small change in your calculation logic:
// calculation for determining compound interest at a yearly rate and over the term
double total = initial * Math.pow((1 + (yearlyrate/100)) , (repeat+1));

Java output with currency formating, percentages, and half_up rounding

JAVA OUTPUT Question, please help.
How to format two outputs, first is to have an ouput using HALF_UP rounding and currency formating and the second is to have an ouput with precentage?
Supporting docs:
(A) orginal assignment
Introduction to Object-Oriented Programming
Programming Assignment – Discount Coupon
A supermarket awards coupons depending on how much a customer spends on groceries. For example, if you spend $50, you will get a coupon worth eight percent of that amount. The following table shows the percent used to calculate the coupon awarded for different amounts spent. Write a program that calculates and prints the value of the coupon a person can receive based on groceries purchased and the amount paid after the discount is applied.
Money Spent
Coupon Percent
Less than $10
No coupon
Between $10 and $60
8%
Between $61 and $150
10%
Between $151 and $210
12%
More than $210
14%
Note, as specified, it is not clear how to handle boundary conditions. For example, what is the coupon percent for $150.25? You should decide how you are going to handle boundary conditions and be sure to explain your choice in the program documentation.
Your program should use a currency instance for formatting dollar amounts and a percent instance for formatting percents. They can both be found in the java.text.NumberFormat package. Use the HALF_UP rounding mode for your currency displays.
Here is a sample run:
run:
Please enter the cost of your grocies: 78.24
You earned a discount of $7.82. (10% of your purchase)
Please pay $70.42. Thank you for shopping with us!
(B) code so far
import java.util.Scanner;
import java.text.NumberFormat;
public class Coupon {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
NumberFormat currency = NumberFormat.getCurrencyInstance();
//Variables
double amountSpent=0;
double couponAmount = 0;
double totalAfterCoupon= 0;
final double lessThanTen = 0.00;
final double betweenTenAndSixity = 0.08;
final double betweenSixtyOneAndOneHundredAndFifty = 0.10;
final double betweenOneHundredAndFiftyOneAndTwoHundredAndTen = 0.12;
final double overTwoHundredAndTen = 0.14;
System.out.print("Please enter the cost of your groceries: ");
amountSpent = input.nextDouble();
if (amountSpent<10 && amountSpent>=0)
{
couponAmount = lessThanTen * amountSpent;
System.out.printf("You earned a discount of ", currency.format(couponAmount), "(0% of your purchase)");
}
else if (amountSpent>=10 && amountSpent<=60.49)
{
couponAmount = betweenTenAndSixity * amountSpent;
System.out.printf("You earned a discount of ", currency.format(couponAmount), "(10% of your purchase)");
}
else if (amountSpent>=60.50 && amountSpent<=150.49)
{
couponAmount = betweenSixtyOneAndOneHundredAndFifty * amountSpent;
}
else if (amountSpent>=150.50 && amountSpent<=210)
{
couponAmount = betweenOneHundredAndFiftyOneAndTwoHundredAndTen* amountSpent;
}
else if (amountSpent>210)
{
couponAmount = overTwoHundredAndTen* amountSpent;
}
else
{
System.out.println("Please enter your total bill between $0.00 or greater. ");
}
System.out.printf("the coupon amount is: %f ", couponAmount);
}
}
Note: I notice you're a newcomer and I'm gonna give you this one for free (We've all need to learn things first), but please keep in mind that ther are certain rules in SO; Asking for homework corrections or bad research related questions aren't appreciated, specially if they both apply. Also as tnw mentioned you should narrow your question down to the specific part of code that's relevant, so that it can easily be reproduced or/and found by others that have the same issue.
In case of the answer to your formatting problem you have some amazing resources at Oracle's official docs, learn how to use their docs and you'll get the hang of Java in no time. On the NumberFormat class they have this: https://docs.oracle.com/javase/tutorial/i18n/format/numberFormat.html , and you will also need the info on locale's in Java: https://docs.oracle.com/javase/8/docs/api/java/util/Locale.html .
What you need to do to use the NumberFormat class is create an instance of the locale you're going to use like: Locale enUSLocale = new Locale.Builder().setLanguage("en").setRegion("US").build();
There are multiple other ways to do this.
And then use this locale to indicate the NumberFormat class what to use:
//Instantiate the NumberFormat:
NumberFormat USFormat = NumberFormat.getCurrencyInstance(enUSLocale);
//And print it:
System.out.println("You earned a discount of " + USFormat.format(couponAmount));
Well I hope this gives you the basis you need to go on and learn to use the docs and other info online!
Goo(gle)d Luck!

Boolean Statement in WHILE loop doesn't make sense?

My while statement just doesn't seem to make sense to me, even though it works.
I want it to calculate the interest only as long as the countYears is less than the timeLimit....so if I set timeLimit to 5, it should only calculate 5 years worth of interest but the way I read the current while statement, it doesn't seem to say that. Maybe I am just reading it wrong?
public class RandomPractice {
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
double intRate, begBalance, balance;
int countYears, timeLimit;
System.out.println("Please enter your current investment balance.");
begBalance = Keyboard.nextDouble();
System.out.println("Please enter your YEARLY interest rate (in decimals).");
intRate = Keyboard.nextDouble();
System.out.println("Please enter how long (in years) you would like to let interest accrue.");
timeLimit = Keyboard.nextInt();
balance = begBalance * (1 + intRate);
countYears = 0;
/* The way I read this while statement is as follows
* "While countYears is GREATER than the timeLimit...calculate the balance"
* This makes no logical sense to me but I get the correct output?
* I want this code to calculate the investment interest ONLY as long as
* countYears is LESS than timeLimit **/
while (countYears >= timeLimit)
{
balance = balance + (balance * intRate);
countYears++;
}
System.out.println(balance);
}
}
That code you have, as it stands, does not generate the correct data, my transcript for eight years at one percent per annum follows:
Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
101.0
In other words, only one year of interest is added rather than eight years.
So either your compiler is totally screwy, your code is not what you think it is, or whatever test data and/or method you're using to check the interest calculation is lacking somewhat.
First, as you foreshadowed, you need to change the condition to be countYears < timeLimit.
In addition, you also need to remove the initial interest calculation before the loop since this would mean you'd get a full year's interest as soon as you deposit the money. With those two changes:
balance = begBalance;
while (countYears < timeLimit) {
balance = balance + (balance * intRate);
countYears++;
}
and you then get the correct value of:
Please enter your current investment balance.
100
Please enter your YEARLY interest rate (in decimals).
.01
Please enter how long (in years) you would like to let interest accrue.
8
108.28567056280801
Your loop isn't being executed at all if you switch it to <= it will be correct.
Right now your output is what is calculated outside of the loop.

Need help Java amortization table calculations

This is my homework it is due Monday the 16th.
I finally got the months to display right but the amounts are wrong.
Also, not necessary but it would be nice to stop and Print something between each loan.
Like loan 1, loan 2, loan 3...
Any help will be appreciated
/*Write the program in Java (without a graphical user interface)
and have it calculate the payment amount for 3 mortgage loans:
- 7 year at 5.35%
- 15 year at 5.5%
- 30 year at 5.75%
Use an array for the different loans.
Display the mortgage payment amount for each loan
and then list the loan balance and interest paid for
each payment over the term of the loan.
Use loops to prevent lists from scrolling off the screen.*/
I have the months correct but the loan amounts are wrong.
import java.io.IOException; //Code that delays ending the program
class MonthlyRhondav4
{
public static void main ( String[] args) throws IOException{
double loanAmount = 200000.00; // $ amount borrowed
double monthlyPayment = 0; // monthly payment for calculating
double loanBalance;
double interestPaid;
double principalPaid;
int paymentCounter;
int lineCounter = 0;
java.text.DecimalFormat dcm = new java.text.DecimalFormat("$,###.00");
int termArray[] = {84, 180, 360}; // Different loan terms in months
double interestArray[] = {0.0535, 0.055, 0.0575};// Different interest rates for the loan
int k =0;// gonna be paymentIndex
/*Code to start the payment list*/
System.out.print("\n\nPlease Press Enter to Continue to the 3 Different Amortization Lists");
System.out.println ();
System.out.println ();
System.in.read();
System.in.read();
/*Display columns*/
System.out.println("Month \t Loan Amount Left\tInterest\t\tPrincipal \n"); //Prints headers for columns
System.out.println ();
/*Loop to calculate and print monthly payments*/
//for(k=0; k<3; k++){// k is going to be paymentIndex to loop through index
for (k = 0; k < interestArray.length; k++) {
for(paymentCounter =1; paymentCounter <= termArray[k]; paymentCounter++) // months through array
{
/********TROUBLE HERE***************************************************************************************/
monthlyPayment = ((loanAmount * (interestArray[k]) * termArray[k]) + loanAmount) / (termArray[k] * 12);
interestPaid = loanAmount*(interestArray[k]/12); //interest paid through array
principalPaid = monthlyPayment-loanAmount*(interestArray[k]/12); //principal paid
/*need to fig monthly payment+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
System.out.println(paymentCounter + "\t" + dcm.format(loanAmount) + "\t\t" + dcm.format(interestPaid) + "\t\t\t" + dcm.format(principalPaid));
lineCounter++; //Increment the display counter
if (lineCounter > 11 && paymentCounter < termArray[k]*12) //Check to see if 12
{
System.out.println ("Please Press Enter to Continue the List" ); //Code to delay ending the program
System.in.read();
System.in.read();
lineCounter = 0;
}
}
loanAmount = (loanAmount - (monthlyPayment-loanAmount*(interestArray[k]/12))); //Calculate new loan amount
}
}//ends public static void main
}//ends public class
One observation -- you're not doing anything with the loan balance. The reason why nothing is changing is that having computed the interest and principal amounts of a given payment, you're not reducing the loan balance by the principal portion of the payment. You need to change your code to display the current loan balance and to compute the principal/interest split from the current loan balance and not the original loan amount.
Edited
Ok -- I see you were trying to update the balance, but you have it outside the loop for the loan. That needs to be inside the loop so that it is updated for each payment. Also, you have things like loanAmount * (interestArray[k] / 12) over and over again. Consider using variables, such as
double interestPaid = loanAmount * (interestArray[k] / 12)
This will make your code easier to read and more maintainable since if you find a mistake in the calculation, you only have to fix the mistake in one place rather than having to fix it everywhere you had the calculation.
I also don't see where you're calculating the monthly payment. That's a function of the original loan amount, number of payments, and interest rate. Remember, the monthly payment is fixed and the interest/principal split of each payment will change as the loan is paid down. You might find http://en.wikipedia.org/wiki/Mortgage_calculator useful to figure out the formula for the monthly payment.
first : never ever use double to calculate something... That's an advice you have to remember. If you don't want to trust me, please search Google for "java double computation" or something like that, and you'll see. Or read the excellent book "Effective Java"
BigDecimal class is there to have correct numbers in Java
A lot of mistakes. For instance you never set the monthlyPayment to anything but 0. You also do not use loanBalance. loanAmount should be a constant. You can also simplify redundant calculations. Example:
interestPaid = loanBalance*(interestArray[k]/12);
principalPaid = monthlyPayment-interestPaid;
instead of
interestPaid = loanBalance*(interestArray[k]/12);
principalPaid = monthlyPayment-loanBalance*(interestArray[k]/12);
I am also not sure you have the correct interest rate formulas, but am not going to check until you remove some of the more obvious errors.

interest calculation

Here's what I got. A linkedList of objects of Customer class of different account types (Savings,current and fixed). Each Customer object has a LinkedList of transactions(another class) as an attribute. 2 types of transactions can be made i.e Debit(withdrawal) or Credit(deposit). Given: A savings account can go into negative while the other two accounts can not. No debit transactions (no withdrawals) from the Fixed account allowed.
if the account balance is positive then the interest rate is 0.0003 while if the account balance is negative (only possible for Saving account)the rate is -0.002. The interest is calculated as follows:
For positive interest, it is based on the money that has
been in the account for the last 24 hours (i.e. from midnight to midnight). For example, if
you have $100 at hour 0 but you have withdrawn $50 at hour 1 and deposited back $50
at hour 2, you will be seen as having only $50 staying in your account for 24 hours at end
of the day (hour 24). At hour 24, the money in your account will be $100 plus the daily
interests computed according to $50.
For negative interest, it is based on the sum of the largest negative money that you owe
the bank on that day. If you borrow money from the bank, they will charge you interest
even if you return the money 1 minute later. For example, if your saving account has
$100 at hour 0 but you withdraw $200 at hour 22 and then deposit $1000 back at hour
23. You will not be paid any positive interest by today mid-night but will be charged for
negative interest for borrow $100 from the bank for today.
For a savings account with initially $566.00 and transactions on the account are as follows:
debit:50 (date:11-09-2008), debit:500(15-09-2008); credit:200(22-09-2008); debit:500(23-09-2008 ).
the sample calculation is given as:
(((566*1.0003^10-50)*1.0003^4-500)*1.0003^8+200-500)*1.002^8 ~= 286.17.
I get some figure of the order of 1377.68 which obviously doesn't match.
Here's what i have for the savings account but i'm pretty sure it's wrong. My question is how to calculate the interest when looping through the transactions for each customer. my calculation is wrong. so i would appreciate it if someone can help me fix the logic
public void update(double rate){ // Savings account interest calc
Transactions ctr = new Transactions();
Node<Transactions> counter = new Node<Transactions>(ctr);
counter=this.trans.head;
int i=0;
double negRate = -0.002;
double posRate = 0.0003;
double updatedBal = this.get_balance();
while(counter!=null){
if (updatedBal >0){
if(trans.getItem(i).AccType.equals("Crebit")){
double exponent = Double.parseDouble(trans.getItem(i).get_Date().substring(0, 2));
updatedBal= (updatedBal*(Math.pow((1+ posRate),exponent-1))+trans.getItem(i).get_Amount());
}
else if(trans.getItem(i).AccType.equals("Debit")){
double exponent = Double.parseDouble(trans.getItem(i).get_Date().substring(0, 2));
updatedBal= (updatedBal*(Math.pow((1+ posRate),exponent-1))-trans.getItem(i).get_Amount());
}
}
else
{
if(trans.getItem(i).AccType.equals("Crebit")){
double exponent = Double.parseDouble(trans.getItem(i).get_Date().substring(0, 2));
updatedBal= (updatedBal*(Math.pow((1+ negRate),exponent-1))+trans.getItem(i).get_Amount());
}
else if(trans.getItem(i).AccType.equals("Debit")){
double exponent = Double.parseDouble(trans.getItem(i).get_Date().substring(0, 2));
updatedBal= (updatedBal*(Math.pow((1+ negRate),exponent-1))-trans.getItem(i).get_Amount());
}
}
counter=counter.next;
}
this.set_balance(updatedBal);
}
Your code has trans.getItem(i).AccType.equals("Crebit") in two places. Presumably that should be Credit. If the value of the AccType field of the transaction items is using the correct spelling, then your if blocks won't "see" the credit transactions when computing the interest and that could lead to a wrong answer.

Categories

Resources