I've only just begun programming, and I find most of my resources to be incredibly unhelpful. Hopefully you guys can help!
My program runs until it gets to the display methods, and then it just stops. No errors, and no build successful. It just continues with the user input. Any ideas?
Here is all of the program. I created a separate class for the object as well. Let me know if you think the problem could be there. Thanks!
import java.util.Scanner;
public class HernandezMortgageCalculator {
public static void main(String[] args) {
programDescription();
System.out.println();
MortgageLoan mortgageLoan1 = new MortgageLoan();
Scanner userInput = new Scanner(System.in);
System.out.println();
System.out.println("Please enter the home buyer's last name: ");
String lastName = userInput.nextLine();
System.out.println("Please enter the home's zip code: ");
String zipCode = userInput.nextLine();
System.out.println("Please enter the home value: ");
double homeValue = userInput.nextDouble();
System.out.println("Please enter the annual interest rate: ");
double annualInterestRate = userInput.nextDouble();
mortgageLoan1.setLoanIdentifier(mortgageLoan1.getLoanIdentifier());
mortgageLoan1.setHomeValue(userInput.nextDouble());
mortgageLoan1.setLoanAmount();
mortgageLoan1.setAnnualInterestRate(userInput.nextDouble());
System.out.println();
System.out.println();
displayLoanDetails(mortgageLoan1);
displayMortgageResults(mortgageLoan1);
}
public static void programDescription() {
System.out.println("This program implements a Mortgage Calulator");
System.out.println();
System.out.println("Given a home's purchase price and loan's annual" +
"interest rate, it will compute the monthly" +
"mortgage payment, which includes taxes, " +
"insurance principle and interest.");
}
public static void displayLoanDetails(MortgageLoan mortgageLoan1){
System.out.println();
System.out.println("Loan Details");
System.out.printf(" Loan identifier %f "
+ mortgageLoan1.getLoanIdentifier());
System.out.println();
System.out.printf(" Loan amount %.2f "
+ mortgageLoan1.getLoanAmount() );
System.out.println();
System.out.printf(" Loan length %f "
+ mortgageLoan1.getLengthOfLoan() + " years");
System.out.println();
System.out.printf(" Annual Interest Rate %.3f"
+ mortgageLoan1.getAnnualInterestRate() + "%");
System.out.println();
}
public static void displayMortgageResults (MortgageLoan mortgageLoan1) {
double monthlyPropertyTax = mortgageLoan1.calcMonthlyPropertyTax();
double monthlyInsurancePremium =
mortgageLoan1.calcMonthlyInsurancePremium();
double monthlyPrincipleAndLoan =
mortgageLoan1.calcMonthlyPrincipleAndLoan();
double totalMonthlyMortgage = monthlyPropertyTax + monthlyInsurancePremium
+ monthlyPrincipleAndLoan;
System.out.println();
System.out.println("Monthly Mortgage Payment");
System.out.printf(" Monthly Taxes %.2f",
monthlyPropertyTax);
System.out.println();
System.out.printf(" Monthly Insurance %.2f",
monthlyInsurancePremium);
System.out.println();
System.out.printf(" Monthly Principle & Interest %.2f",
monthlyPrincipleAndLoan);
System.out.println();
System.out.println(" --------");
System.out.println();
System.out.printf(" Total Monthly Mortage Payment %.2f",
totalMonthlyMortgage);
}
public class MortgageLoan {
private String loanIdentifier;
private double homeValue;
private double downPayment;
private double loanAmount;
private int lengthOfLoan;
private double annualInterestRate;
public MortgageLoan() {
loanIdentifier = "";
homeValue = 0.0;
downPayment = 10.0;
loanAmount = 0.0;
lengthOfLoan = 30;
annualInterestRate = 0.0;
}
public static char firstFour(String lastName){
char result = lastName.charAt(0);
result += lastName.charAt(1);
result += lastName.charAt(2);
result += lastName.charAt(3);
return result;
}
public static char firstThree(String zipCode){
char result = zipCode.charAt(0);
result += zipCode.charAt(1);
result += zipCode.charAt(2);
return result;
}
public static String lastNameZipCode(String lastName, String zipCode) {
String result = "";
result = lastName.toUpperCase();
result += firstFour(lastName);
result += firstThree(zipCode);
return result;
}
void setLoanIdentifier(String lastNameZipCode) {
loanIdentifier = lastNameZipCode;
}
void setHomeValue(double newHomeValue) {
homeValue = newHomeValue;
}
void setLoanAmount() {
double newLoanAmount = homeValue - homeValue * (downPayment/100);
loanAmount = newLoanAmount;
}
void setAnnualInterestRate(double newAnnualInterestRate) {
annualInterestRate = newAnnualInterestRate;
}
public String getLoanIdentifier() {
return loanIdentifier;
}
public double getLoanAmount(){
return loanAmount;
}
public int getLengthOfLoan(){
return lengthOfLoan;
}
public double getAnnualInterestRate(){
return annualInterestRate;
}
public double calcMonthlyPropertyTax() {
final double HOME_ASSED_VALUE_PERCENTAGE = 0.85;
final double ANNUAL_PROPERTY_TAXES_PERCENTAGE = 0.0063;
final double ADMIN_FEE = 35.00;
double homeAssessedValue = homeValue * HOME_ASSED_VALUE_PERCENTAGE;
double annualPropertyTaxes = (homeAssessedValue *
ANNUAL_PROPERTY_TAXES_PERCENTAGE + ADMIN_FEE);
double monthlyPropertyTax = annualPropertyTaxes/12;
return monthlyPropertyTax;
}
public double calcMonthlyInsurancePremium() {
final double ANNUAL_PREMIUM_PERCENTAGE = .0049;
double annualInsurancePremium = .0049 * homeValue;
double monthlyInsurancePremium = Math.round(annualInsurancePremium/12);
return monthlyInsurancePremium;
}
public double calcMonthlyPrincipleAndLoan(){
double monthlyInterestRate = annualInterestRate/100/12;
double Factor = Math.exp((lengthOfLoan*12) * Math.log
(monthlyInterestRate + 1));
double monthlyPrincipleAndLoan = (Factor * monthlyInterestRate *
loanAmount)/(Factor - 1);
return monthlyPrincipleAndLoan;
}
}
Related
I am working on a school project and I am pretty much done but have been stuck in a detail. I am asking the user to enter their starting balance and the interest rate, to make it easier for the user just asking to enter a whole number like 1, 2, 3, etc. Example, if they enter 1000 in starting balance and 9% in the interest rate the result would 1750.00, the expected result is 1007.50 which comes when the user enters .09%, is there a way to change any number the user enters to that so when they enter 9 it transforms it into .09. If you run the code, enter starting balance and rate and then select "M", you will see those numbers. Any ideas will be appreciated, here is the code:
///BankDemo class
import java.util.Scanner;
public class BankDemo {
#SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
float startingBalance;
float interestRate;
String userInput;
System.out.print("Enter beginning balance :$");
startingBalance = keyboard.nextFloat();
System.out.print("Enter interest rate(whole number) :%");
interestRate = keyboard.nextFloat();
System.out.println("Enter D for deposit" + "\nEnter W to Withdraw" + "\nEnter B for Balance" +
"\nEnter M for Monthly Process" + "\nEnter E to Exit");
userInput = keyboard.next().toLowerCase();
float bal = startingBalance;
float rate = interestRate;
BankAccount ba = new BankAccount(startingBalance, interestRate);
SavingsAccount sv = new SavingsAccount(bal, rate);
if("d".equals(userInput)) {
ba.deposit();
} else if("w".equals(userInput)) {
ba.withdraw();
} else if("b".equals(userInput)) {
ba.totalBalance();
} else if("m".equals(userInput)) {
ba.monthlyProcess();
} else if("e".equals(userInput)) {
ba.exit();
} else {
System.out.print("Error, option to valid");
}
}
}
///BankAccount Class
import java.util.Scanner;
public class BankAccount {
protected float balance;
protected float numDeposits;
protected float numWithdrawals;
protected float annualRate;
protected float monthlyServCharg;
public BankAccount() {
balance = 0;
numDeposits = 0;
numWithdrawals = 0;
annualRate = 0;
monthlyServCharg = 0;
}
public BankAccount(float startingBalance, float interestRate) {
balance = startingBalance;
annualRate = interestRate;
}
public void deposit() {
float valueD;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to deposit :$");
valueD = keyboard.nextFloat();
balance += valueD;
numDeposits++;
}
public void withdraw() {
float valueW;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the amount you want to withdraw :$");
valueW = keyboard.nextFloat();
if(valueW < 1) {
System.out.println("Error: Must enter positive value\n");
}
balance -= valueW;
numDeposits++;
}
public void totalBalance() {
System.out.print("Balance is: " + balance);
}
public void calcInterest() {
float monRate = annualRate / 12;
float monInt = balance * monRate;
balance += monInt;
}
public void monthlyProcess() {
calcInterest();
balance -= monthlyServCharg;
numWithdrawals = 0;
numDeposits = 0;
monthlyServCharg = 0;
System.out.printf("Your Balance after Monthly process is: %.2f", balance);
}
public void exit() {
totalBalance();
System.out.print("\nThank you. Bye");
}
}
In your overload constructor, set annualRate equal to (interestRate / 100) to convert it to a percentage. Also, as a side node, you don't need to initialize all the variables on the default constructor because they're initialize to 0 since they're primitive data types.
While I was creating an application below, I want to know if there would be a way to calculate the total price by making a public void in the second class AllFood, instead of stating each prices in the class Tester. Since the price is different for every object, I want to know if I could put all of the prices in a one statement and calculate the total price so I could just put food.getTotalPrice in the print section.
The Tester.java:
public class Tester {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AllFood myobj = new AllFood();
System.out.print("Enter number of hamburgers : ");
int hamq = scan.nextInt();
myobj.food("hamburger",9.0 , 33.0, 1.0);
double price1 = hamq * 1.85;
System.out.print("\n" + "Enter number of salads : ");
int salq = scan.nextInt();
myobj.food("salad", 1.0 , 11.0, 5.0);
double price2 = salq*2.00;
System.out.print("\n" + "Enter number of french fries : ");
int ffq = scan.nextInt();
myobj.food("french fry", 11.0 , 36.0, 4.0);
double price3 = ffq * 1.30;
System.out.print("\n" + "Enter number of sodas : ");
int sodq = scan.nextInt();
myobj.food("soda", 0.0 , 38.0, 0.0);
double price4 = sodq * 0.95;
double totalPrice = price1 + price2 + price3 + price4;
DecimalFormat money = new DecimalFormat("$##.##");
System.out.print("\n" + "Your order comes to : " + money.format(totalPrice));
}
}
The AllFood.java:
public class AllFood {
private String food;
private double price, total, quantity, fat, carbs, fiber;
public AllFood() {
food ="";
quantity = 0;
fat=0;
carbs=0;
fiber =0;
price=0;
}
public AllFood(String fo, double q, double f, double c, double fi, double p) {
food=fo;
quantity = q;
fat= f;
carbs = c;
fiber = fi;
price = p;
}
public void food(String fo, double f,double c, double fi) {
System.out.println("Each " + fo + " has " + f + "gs of fat, "+ c + "gs of carbs, and " + fi + "gs of fiber.");
}
}
To be able to get the total price of the food from AllFood you need to store the list of foods. This means having another class Food to store the single foods objects:
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
AllFood myobj = new AllFood();
System.out.print("Enter number of hamburgers : ");
int hamq = scan.nextInt();
double price1 = hamq * 1.85;
Food hamburger = new Food("hamburger",price1,hamq,9.0 , 33.0, 1.0);
System.out.print(hamburger.toString());
myobj.addFood(hamburger);
System.out.print("\n" + "Enter number of salads : ");
int salq = scan.nextInt();
double price2 = salq*2.00;
Food salad = new Food("salad",price2,salq,1.0 , 11.0, 5.0);
System.out.print(salad.toString());
myobj.addFood(salad);
System.out.print("\n" + "Enter number of french fries : ");
int ffq = scan.nextInt();
double price3 = ffq * 1.30;
Food frenchFry = new Food("french fry",price3,ffq,11.0 , 36.0, 4.0);
System.out.print(frenchFry.toString());
myobj.addFood(frenchFry);
System.out.print("\n" + "Enter number of sodas : ");
int sodq = scan.nextInt();
double price4 = sodq * 0.95;
Food soda = new Food("soda",price4,sodq,11.0 , 36.0, 4.0);
System.out.print(soda.toString());
myobj.addFood(soda);
DecimalFormat money = new DecimalFormat("$##.##");
System.out.print("\n" + "Your order comes to : " + money.format(myobj.getTotalPrice()));
}
}
This is the class AllFoods:
public class AllFood {
private List<Food> foods;
public AllFood() {
this.foods=new ArrayList<>();
}
public void addFood(Food food) {
this.foods.add(food);
}
public double getTotalPrice() {
double price = 0;
for(Food food:foods) {
price += food.getPrice();
}
return price;
}
}
And finally the class Food:
public class Food {
private String name;
private double price, quantity, fat, carbs, fiber;
public Food(String name, double price, double quantity, double fat, double carbs, double fiber) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.fat = fat;
this.carbs = carbs;
this.fiber = fiber;
}
#Override
public String toString() {
return "Each " + name + " has " + fat + "gs of fat, " + carbs + "gs of carbs, and " + fiber + "gs of fiber.";
}
public double getPrice() {
return price;
}
}
When I run the program and and put in a couple mortgages and then end the program it prints out the entire array of objects, mortgageArray[], but for some reason it is only printing out the last mortgage you entered. Not sure why can anybody help me out? I think the problem may lie when instantiating the objects into the array.
Mortgage Class
import java.util.*;
import java.lang.Math.*;
import java.text.DecimalFormat;
public class Mortgage {
private static int loanAmount;
private static int term;
private static double interestRate;
private static String accountNum;
private static String lastName;
private static double monthlyPayment;
private static double totalPayment;
public Mortgage(int loanAmount1, int term1, double interestRate1, String accountNum1){
loanAmount = loanAmount1;
term = term1;
interestRate = interestRate1;
accountNum = accountNum1;
}
public void promotional(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
lastName = getLastName();
accountNum = getAccountNum();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public void unique(){
Mortgage m = new Mortgage();
m.storeLastName();
m.storeAccountNum();
m.storeLoanAmount();
m.storeInterestRate();
m.storeTerm();
monthlyPayment = m.calcMonthlyPayment();
totalPayment = m.calcTotalPayment();
}
public Mortgage(){
//dummy constructor
}
public static int getLoanAmount(){
return loanAmount;
}
public void storeLoanAmount(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the amount of the loan (Ex:75000): ");
int loanAmount1 = s.nextInt();
while(loanAmount1 < 75000 || loanAmount1 > 1000000){
System.out.println("\tValid Loan Amounts are $75000-$1000000");
System.out.println("\tPlease re-enter loan amount without $ or commas (Ex:75000): ");
loanAmount1 = s.nextInt();
}
loanAmount = loanAmount1;
}
public static int getTerm(){
return term;
}
public void storeTerm(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number of years for the loan: ");
int term1 = s.nextInt();
while(term1 < 10 || term1 > 40){
System.out.println("\tValid Loan Terms are 10-40");
System.out.println("\tPlease re-enter valid number of years: ");
term1 = s.nextInt();
}
term = term1;
}
public static double getInterestRate(){
return interestRate;
}
public void storeInterestRate(){
Scanner s = new Scanner(System.in);
System.out.println("Enter yearly interest rate (Ex: 8.25): ");
double interestRate1 = s.nextDouble();
while(interestRate1 < 2 || interestRate1 > 7){
System.out.println("\tValid Interest Rates are 2% - 7%");
System.out.println("\tPlease re-enter valid yearly interest rate (Ex: 8.25): ");
interestRate1 = s.nextDouble();
}
interestRate = interestRate1;
}
public String getLastName(){
return lastName;
}
public void storeLastName(){
Scanner s = new Scanner(System.in);
System.out.println("Enter customer's Last Name Only: ");
String lastName1 = s.nextLine();
lastName = lastName1;
}
private double calcMonthlyPayment(){
int months = term * 12;
double monthlyInterest = (interestRate / 12 / 100);
double monthlyPay = (loanAmount * monthlyInterest) / (1 - Math.pow(1+ monthlyInterest, -1 * months));
return monthlyPay;
}
private double calcTotalPayment(){
double totalPay = calcMonthlyPayment() * term * 12;
return totalPay;
}
public String getAccountNum(){
return accountNum;
}
public void storeAccountNum(){
StringBuilder accountNum1 = new StringBuilder();
Random rand = new Random();
int accNum = rand.nextInt(9900);
accNum += 100;
accountNum1.append(lastName.substring(0,4));
accountNum1.append(accNum);
accountNum = accountNum1.toString();
}
public String toString(){
DecimalFormat df = new DecimalFormat("#,###.00");
String strMonthlyPayment = ("$" + df.format(calcMonthlyPayment()));
String strTotalPayment = ("$" + df.format(calcTotalPayment()));
return("Account Number: " + accountNum + "\nThe monthly payment is " + strMonthlyPayment + "\nThe total payment is " + strTotalPayment);
}
}
MortgageApp Class
import java.util.*;
public class MortgageApp {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Mortgage m = new Mortgage();
int size = 10;
Mortgage [] mortgageArray = new Mortgage [size];
int index = 0;
for(index = 0; index < size; index++){
int choice;
System.out.println("\nPlease choose from the following choices below:");
System.out.println("\t1) Promotional Load (preset loan amount, rate, term)");
System.out.println("\t2) Unique Loan (enter in loan values)");
System.out.println("\t3) Quit (Exit the program)");
System.out.println("\n\t Please enter your selection (1-3): ");
choice = s.nextInt();
while(choice < 1 || choice > 3){
System.out.println("\t\tInvalid Choice. Please select 1, 2, or 3: ");
choice = s.nextInt();
}
if(choice == 1){
m.promotional();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(250000, 20, 3.2, accountNum1);
System.out.println("PROMOTIONAL LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 2){
m.unique();
int loanAmount = m.getLoanAmount();
int term = m.getTerm();
double interestRate = m.getInterestRate();
String accountNum1 = m.getAccountNum();
mortgageArray[index] = new Mortgage(loanAmount, term, interestRate, accountNum1);
System.out.println("UNIQUE LOAN...:");
System.out.println(mortgageArray[index].toString());
}
else if(choice == 3){
System.out.println("\nPROGRAM COMPLETE");
System.out.println("Contents of Array...");
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[j].toString() + "\n");
}
}
index = 10;
}
}
}
}
The problem is with your loop at the end
for(int j = 0; j < 10; j++){
if(mortgageArray[j] != null){
System.out.println(mortgageArray[1].toString() + "\n");
}
}
It always prints the element at index 1.
Should be
System.out.println(mortgageArray[j].toString() + "\n");
All your fields in the class Mortgage are static.
To fix this, simply remove the static keyword:
private int loanAmount;
private int term;
private double interestRate;
private String accountNum;
private String lastName;
private double monthlyPayment;
private double totalPayment;
Static fields don't belong to an instance, but to the class that gets instantiated. So everytime you call one of your getter-methods, the previous value (of all your instances) will be overriden.
If you are not familiar with classes and objects in Java, this tutorial might be helpfull for you: Understanding Class Members
I am trying to make a GPA calculator using a while loop with an unknown set of entries. When only one set of information is entered, my program runs fine. If I enter information for more than one class, the totals do not update and I cannot figure out why. Any ideas?
import javax.swing.JOptionPane;
public class GUITestClient {
public static void main(String[] args) {
StudentInfo student = new StudentInfo();
double credits = 0;
double gradePoints = 0;
double gradePointsTot = 0;
double gpa = 0;
String addAnotherClass = null;
String name = JOptionPane.showInputDialog("Please enter your name:");
student.setName(name);
do{
credits = Double.parseDouble(JOptionPane.showInputDialog("Please
enter the credits:"));
student.setCredits(credits);
String grade = JOptionPane.showInputDialog("Please enter your
grade:");
student.setGrade(grade);
addAnotherClass = JOptionPane.showInputDialog("Press "+"Y"+" to
enter More class information");
gradePoints = StudentInfo.addClass(gradePoints, grade);
gradePointsTot += gradePoints;
}while(addAnotherClass.equalsIgnoreCase("y"));
//after loop
student.setGradePoints(gradePointsTot);
StudentInfo.getGPA(credits, gpa, gradePointsTot);
student.setGpa(gpa);
JOptionPane.showMessageDialog(null,
student.displayStudentInformation());
}
}
class StudentInfo {
private String name;
private double totalGradePoints;
private double credits;
private String grade;
private double gpa;
public StudentInfo(){
setGrade(null);
setCredits(0);
setGradePoints(0);
}
public StudentInfo(double credits, double totalGradePoints, String
grade){
setGrade(grade);
setCredits(credits);
setGradePoints(totalGradePoints);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public double getCredits() {
return credits;
}
public void setCredits(double credits) {
this.credits = credits;
}
public double getGradePoints() {
return totalGradePoints;
}
public void setGradePoints(double totalGradePoints) {
this.totalGradePoints = totalGradePoints;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public static double addClass(double totalGradePoints, String grade){
double gradePoints = 0;
double accumGradePoints;
if(grade.equalsIgnoreCase("A")){
gradePoints = 4.0;
}else if(grade.equalsIgnoreCase("B")){
gradePoints = 3.0;
} else if(grade.equalsIgnoreCase("C")){
gradePoints = 2.0;
} else if(grade.equalsIgnoreCase("D")){
gradePoints = 1.0;}
totalGradePoints += gradePoints;
return totalGradePoints;
}
public static double getGPA(double totalGradePoints, double credits,
double gpa){
gpa = (credits * totalGradePoints)/ credits);
return gpa;
}
public String displayStudentInformation(){
String output = "";
output = output + "Name: " + this.getName() + "\n";
output = output + "Total Credits: " + this.getCredits() + "\n";
output = output + "Your grade is: " + this.getGrade() + "\n";
output = output + "Your GPA is:
" + this.getGPA(totalGradePoints, credits, gpa) + "\n";
output = output + "Press any key to continue!" + "\n";
output = output + "gp" + totalGradePoints + "credits" + credits;
return output;
}
}
I have my code running perfectly, except for my return value for the monthly loan calculator. It keeps on returning Infinity for both my monthly payments and total payments. Please help with the formula. This is a homework. All i need to know is if I am implementing the formula incorrectly. I get the feeling that it is somehow trying to divide over 0 and then returning infinity, but I could be wrong.
public class MyLoan
{
private double amountBorrowed;
private double yearlyRate;
private int years;
public double A;
public double n = years * 12;
public MyLoan(double amt, double rt, int yrs)
{
amountBorrowed = amt;
yearlyRate = rt;
years = yrs;
}
public double getAmountBorrowed()
{
return amountBorrowed;
}
public double getYearlyRate()
{
return yearlyRate;
}
public int getYears()
{
return years;
}
public double monthlyPayment()
{
double i = (yearlyRate / 100) / 12;
A = (amountBorrowed) * (i * Math.pow(1+i, n)) / (Math.pow(1+i, n) -1);
return A;
}
public double totalPayment()
{
return A * (years * 12);
}
public String toString()
{
return "Loan: " + "$" + amountBorrowed + " at " + yearlyRate + " for " + years + " years";
}
public static void main(String[] args)
{
final double RATE15 = 5.75;
final double RATE30 = 6.25;
StdOut.println("***** Welcome to the Loan analyzer! *****");
String ans = "Y";
do {
StdOut.print("\n Enter the principle amount to borrow: ");
double amount = StdIn.readDouble();
MyLoan fifteenYears = new MyLoan(amount, RATE15, 15);
MyLoan thirtyYears = new MyLoan(amount, RATE30, 30);
double amount15 = fifteenYears.monthlyPayment();
double total15 = fifteenYears.totalPayment();
double amount30 = thirtyYears.monthlyPayment();
double total30 = thirtyYears.totalPayment();
StdOut.println("===========ANALYSES==========");
StdOut.println(fifteenYears);
StdOut.println("Monthly payment = " + "$" + amount15);
StdOut.println("Total payment = " + "$" + total15);
StdOut.println("");
StdOut.println("");
StdOut.println(thirtyYears);
StdOut.println("Monthly payment = " + "$" + amount30);
StdOut.println("Total payment = " + "$" + total30);
StdOut.println("=============================");
StdOut.print("\n ** Do you want to continue (y/n)? ");
ans = StdIn.readString();
} while (ans.toUpperCase().equals("Y"));
StdOut.println("\n********** Thank you. Come again! **********");
}
}
You should be debugging this yourself, but I'll give you a hint. What is 1^n (where n is a positive integer)? Where, in your code, are you using this construct?
There is many ways to calculate interest and the most common is just
A = amountBorrowed * (yearlyRate / 100) / 12;