Problem Printing From My Method - java

Merged with Java JOptionPane Output.
I am new to Java and I have been going crazy trying to get this to work.
I have been trying to get this Print Method to work for the last couple of hour but I just can't figure out what is wrong with it. I don't get any errors when I run it. I only want one output box to display after all of the calculations have been made.
I need to ask the user the following information and display the output for the following:
Number of loans to compare
House Price
Down Payment
My Problem: Something is a matter with my math and the output box is displaying more than once.
I greatly appreciate any help I can get with this. Thanks In Advance!
package javamortgagecalculator;
import javax.swing.JOptionPane;
public class JavaMortgageCalculator {
public static void main(String[] args) {
int numberOfLoans;
double sellingPrice;
double downPayment;
double loanAmount;
double annualInterestRate = 0.0;
int numberOfYears = 0;
double[] interestRatesArr;
int[] numberOfYearsArr;
double[] monthlyPayment;
//A. Enter the Number Of Loans to compare and Convert numberOfLoansString to int
String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Selling Price of Home Convert homeCostString to double
String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
sellingPrice = Double.parseDouble(sellingPriceString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
downPayment = Double.parseDouble(downPaymentString);
//Get the loanAmount by Subtracting the Down Payment from homeCost
loanAmount = sellingPrice - downPayment;
interestRatesArr = new double[numberOfLoans];
numberOfYearsArr = new int[numberOfLoans];
monthlyPayment = new double[numberOfLoans];
int counter = 1;
for (int i = 0; i < numberOfLoans; i++) {
//Enter the Interest Rate
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
annualInterestRate = Double.parseDouble(annualInterestRateString);
interestRatesArr[i] = (annualInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArr[i] = (numberOfYears);
counter++;
}
printArray(numberOfLoans,
sellingPrice,
downPayment,
loanAmount,
annualInterestRate,
numberOfYears,
interestRatesArr,
numberOfYearsArr,
monthlyPayment);
}
//public static void printArray(int numOfLoans, double price, double dwnPayment, double loanAmt, double[] printRate, int[] printYears) {
public static void printArray(int numberOfLoans2,
double sellingPrice2,
double downPayment2,
double loanAmount2,
double annualInterestRate2,
int numberOfYears2,
double[] interestRatesArr2,
int[] numberOfYearsArr2,
double[] monthlyPayment2){
for (int i = 0; i < numberOfLoans2; i++) {
//Calculate monthly payment
double monthlyPayment = loanAmount2 * annualInterestRate2 / (1 - 1 / Math.pow(1 + annualInterestRate2, numberOfYears2 * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int) (monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPayment2[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPayment2[i] * numberOfYears2 * 12;
//Format to keep totalPayment two digits after the decimal point
//totalPayment = (int) (totalPayment * 100) / 100.0;
//totalPaymentArray[i] = (totalPayment);
StringBuilder sb = new StringBuilder();
int n = 0;
for (int x = 0; x < numberOfLoans2; x++) {
if (n == 0) {
sb.append(String.format("%s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %n", "Selling Price", "Down Payment", "Loan Amount", "Rate", "Years", "Payment"));
}
sb.append(String.format("%s\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t %n", "$" + sellingPrice2, "$" + downPayment2, "$" + loanAmount2, interestRatesArr2[i] + "%", numberOfYearsArr2[i], "$" + monthlyPayment2[i]));
n++;
}
String toDisplay = sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
}

Related

Cannot figure out why loop isn't getting the correct sum

I'm trying to make a mortgage calculator, and for whatever reason it's getting the wrong sum for the principal and the interest. Is it possible that because it's being added up inside of the do-while loop that it gets it wrong? When I run the program it comes up with 8233.68 for the principal and 11423.59 for interest. If you sum them up on a calculator, it should be 8209.30 for principal and 11447.97 for the interest.
double termSelection = 0.0359;
double principal = 325000;
double effectiveMonthlyRate = 0.0029695338579054376;
double monthlyPayment = 1638.1053796234314;
double monthlyInterest = (principal * effectiveMonthlyRate);
double monthlyPrincipal = (monthlyPayment - monthlyInterest);
double closingBalance = (principal - monthlyPrincipal);
int month = 1;
double totalPrincipal = 0;
double totalInterest = 0;
termSelection *= 100;
//monthly payment schedule header
System.out.println("");
System.out.printf("%nInterest Rate: %.2f%%", termSelection);
System.out.printf("%n%53s", "Monthly Payment Schedule");
termSelection /= 100;
//monhtly payment schedule body
System.out.printf("%n%5s%14s%15s%15s%15s%15s", "Month", "Open Bal", "Payment", "Princ", "Interest", "Closing Bal");
do{
System.out.printf("%n%5s%14.2f%15.2f%15.2f%15.2f%15.2f", month, principal, monthlyPayment, monthlyPrincipal, monthlyInterest, closingBalance);
month++;
principal = closingBalance;
monthlyInterest = principal * effectiveMonthlyRate;
monthlyPrincipal = monthlyPayment - monthlyInterest;
closingBalance = principal - monthlyPrincipal;
totalPrincipal = totalPrincipal + monthlyPrincipal;
totalInterest = totalInterest + monthlyInterest;
}
while (month <= 12);
System.out.println("");
for (int count = 0; count <= 80; count++){
System.out.print('=');
}
System.out.printf("%n%5s%44.2f%15.2f", "Ttls", totalPrincipal, totalInterest);
The problem is that you are doing calculation before you even enter the loop
double closingBalance = (principal - monthlyPrincipal);
should be
double closingBalance = (principal);
output
Ttls 8209.30 11447.97
You recalculate initial values of monthlyInterest and monthlyPrincipal on first iteration of the loop and then add them to totals. Add them to totals first and then recalculate.
do {
System.out.printf("%n%5s%14.2f%15.2f%15.2f%15.2f%15.2f", month, principal, monthlyPayment, monthlyPrincipal, monthlyInterest, closingBalance);
principal = closingBalance;
totalPrincipal += monthlyPrincipal;
totalInterest += monthlyInterest;
monthlyInterest = principal * effectiveMonthlyRate;
monthlyPrincipal = monthlyPayment - monthlyInterest;
closingBalance = principal - monthlyPrincipal;
month++;
} while (month <= 12);

Using methods to calculate account balance

I am trying to return a bank balance that takes into account the number of years, the amount in the account and the interest rate. However, when I compile the program, I receive an error on the return statement. When I try putting the return outside the loop, i get another error.
In Loop:
Exercise3.java:35: error: missing return statement
Out of Loop:
Exercise3.java:34: error: cannot find symbol
}return sum;
^
symbol: variable sum
location: class Exercise3
1 error
The code is below
import java.util.Scanner;//import scanner class
public class Exercise3{//Name of prograsm
public static void main(String args[]){ //declare main method
Scanner sc = new Scanner(System.in);//Declare the scanner method
System.out.println("How much in in your account?");//ask user for balance details
double accBalance = sc.nextDouble();//Store balance details
System.out.println("how many years are you saving? "); //ask the user for how many years they will be saveing
double yrSaving = sc.nextDouble();// Amount of years stored
System.out.println("What is the yearly interest rate ?");//ask the user for the interest rate
double rateInterest = sc.nextDouble();//store the interest rate
double results = balanceAccount(accBalance, yrSaving, rateInterest);//invoke the methofd
System.out.println(results); //print thte results of the method
}
////////////////////////////////////////////////////////////////////////////////
//Calculate the balance of the account method
public static double balanceAccount(double accBalance, double yrSaving, double rateInterest){
double rate = rateInterest / 100;
for(int x = 0; x <= yrSaving; x++){
double sum = accBalance*rate;
return sum;
}
}
}
Use this as a body for your method. Your problem was that you were not returning in every scenario. Also your sum logic was faulted.
double rate = rateInterest / 100;
double sum = 0;
for(int x = 0; x <= yrSaving; x++){
sum += accBalance * rate;
}
return sum;
this is how i did it
public static double balanceAccount(double accBalance, double yrSaving, double rateInterest){
double rate = rateInterest / 100;
double sum = 0;
double finishAmt = 0;
sum += accBalance * rate;
finishAmt = sum * yrSaving +(accBalance);
return finishAmt;
}
}

How to do an array in a loop

I am making an investment calculator.
So I will be doing a math problem and I want to loop it through each array and there will be 12 of them.
So let's say I am going to invest $1000 with a rate return of 4.5%.
So I will need to do 1000 * 0.045 + 1000 = 1,045 that equals one month. Then I need to do 1,045 * 0.045 + 1,045 = 1,092 that would equal the second month and how would I have it go through a loop like that?
Would I use a for loop? or?
This is what I have so far maybe you'll get it better by reading it. But I still need to create a loop that would like the example I gave above.
public class SimpleInvestment {
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double [] num = new double [11];
printWelcome();
double investTotal = getInvestAmount();
double rateTotal = getRate();
}
public static void printWelcome()
{
System.out.println("Welcome to the Investment Calulator");
}
public static double getInvestAmount()
{
double amountInvest;
System.out.print("Hou much will you be investing? ");
amountInvest = input.nextDouble();
while (amountInvest <= 0)
{
System.out.println("Amount must be greater than 0. Try again.");
System.out.print("How much will you be investing? ");
amountInvest = input.nextDouble();
}
return amountInvest;
}
public static double getRate()
{
double rate;
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
while (rate < 0 )
{
System.out.println("Rate must be greater than 0. Try again.");
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
}
return rate;
}
public static void calculateInterst( double num[], double investTotal, double rateTotal)
{
double total;
rateTotal = rateTotal / 100;
total = investTotal * rateTotal + investTotal;
}
}
You can use a while or for loop. In this example I used a for loop.
There is documentation in the code to walk you through the logic.
public static void calculateInterest(double num, double investTotal, double rateTotal) {
double total; //keep the total outside loop
rateTotal = rateTotal / 100; //your percent to decimal calculation
total = investTotal * rateTotal + investTotal; //intial calculation
for (int i = 1; i < num; i++) {//for loop starting at 1 because we alreay calculated the first
total += (total * rateTotal);//just calculate the rate of change
}
System.out.println(total);//either output it or return it. Whatever you want to do from here.
}
I hope this helps!
You can use below code:
where months is the investment duration in months,
investment is the amount that is being invested,
rate is the interest rate. e.g. 0.045
public static double calculateTotal(int months, double investment, double rate) {
double total = investment;
for (int i=1; i <= months; i++) {
total = total + (total * rate);
}
return total;
}

How to get results from another method into another method using java?

I made a simple grade system for fun. I'm trying to apply the total of grades and add it to an equation in my getApercent() method. However, I keep getting errors and don't know what to do.
package gradesystem;
import java.util.Scanner;
public class Gradesystem {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Gradesystem gs = new Gradesystem();
// TODO Auto-generated method stub
int Acount,Bcount,Ccount,Dcount,Fcount;
double ap,bp,cp,dp,fp;
System.out.println("Enter the amount of A's");
Acount = keyboard.nextInt();
System.out.println("Enter the amount of B's");
Bcount = keyboard.nextInt();
System.out.println("Enter the amount of C's");
Ccount = keyboard.nextInt();
System.out.println("Enter the amount of D's");
Dcount = keyboard.nextInt();
System.out.println("Enter the amount of F's");
Fcount = keyboard.nextInt();
int grades;
ap = getApercent(Acount);
System.out.println(ap);
bp = getBpercent(Bcount);
System.out.println(bp);
cp = getCpercent(Ccount);
System.out.println(cp);
dp = getDpercent(Dcount);
System.out.println(dp);
fp = getFpercent(Fcount);
System.out.println(fp);
}
public static void Totalgrades(int acount, int bcount, int ccount, int dcount, int fcount){
int totalofgrades = acount + bcount + ccount + dcount + fcount;
System.out.print(totalofgrades);
}
public static double getApercent(int a){
double ap;
ap = (a/a * 100) + 0.5;
return Math.round(ap);
}
public static double getBpercent(int b){
double bp;
bp = (b/b * 100) + 0.5;
return Math.round(bp);
}
public static double getCpercent(int c){
double cp;
cp = (c/c * 100) + 0.5;
return Math.round(cp);
}
public static double getDpercent(int d){
double dp;
dp = (d/d * 100) + 0.5;
return dp;
}
public static double getFpercent(int f){
double fp;
fp = (f/f * 100) + 0.5;
return fp;
}
}
A little bit of guessing here. But the methods that calculate the percentage seem off. Again, assuming; but to calculate the percentage of a whole you would use the following formula percentage = part/whole * 100
e.g.
we have 9 grades and 3 are A's, 3 are B's, 2 are C's, 1 is D's, and 0 are E's.
Then I'd expect the percentages to be as follows:
33% A // 3 / 9 * 100
33% B // 3 / 9 * 100
22% C // 2 / 9 * 100
11% D // 1 / 9 * 100
0% E // 0 / 9 * 100
One other thing to point out is the the operator / with two ints does integer division. So 3 / 9 == 0.
You could replace all the specific methods with a more generic version.
public static double getPercentage(int gradeCount, int totalNumberOfGrades) {
double percentage = ( gradeCount / (double) totalNumberOfGrades * 100);
return Math.round(percentage);
}

Class won't calculate what it should, also: sorting arrays of objects?

I'm trying to write a program that will allow the user to create "loan" objects and measure the total amount that they have to pay after putting it through an interest equation. I'm having two problems with it that i've been messing with for a few hours but can't figure out for some reason. The biggest problem is that the class that is supposed to calculate the total payment of the loan after plugging in variables, but it ALWAYS returns zero and I can't figure out why. Is it a problem with syntax? I created a test loan class to test out the program that creates ten random loans with ten random time lengths and both the "totalPay" and the "monthlyPay" (which is dependent on totalPay) is always zero.
The second problem is that I was trying to sort the ten random loans based on the numberOfYears of the loan, but I can't get it to work! I tried a few methods for sorting and the one I included is the most recent and probably the one that's the dumbest hahaha but it's the one that I was playing with most recently. I've included all the code below, any ideas?
Loan class:
(it's a little long but the important thing is just the main loan class, totalPayment, and monthlyPayment )
public class Loan {
double annualInterestRate = 2.5;
int numberOfYears = 1;
double loanAmount = 1000;
double base;
double exponent;
double totalPay;
String summary;
double monthly;
String[] list = new String[10];
String s;
/**
* creates default loan with 2.5 annual interest rate 1 year and 1000$
*/
public Loan(){
}
/**
* totalPay = amount(1+rate/12)^(year*12)
*
* #param anualInterestRate
* #param numberOfYears
* #param loanAmount
*/
public Loan(double anualInterestRate, int numberOfYears, double loanAmount){
base = (double) ( loanAmount * (1+anualInterestRate/12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
/**
*
* #return total payment
*/
public double totalPayment(){
return this.totalPay;
}
/**
*
* #return Monthly Payment
*/
public double monthlyPayment(){
monthly = (totalPay/12);
return monthly;
}
}
TestLoan:
import java.util.Random;
public class TestLoan {
public static void main (String[] args){
Random r = new Random();
Loan[] list = new Loan[10];
for (int i = 0; i < 10; i++){
Loan x = new Loan();
list[i] = x;
System.out.println(list[i].toString());
}
System.out.println();
System.out.println();
for (int i = 0; i < 9; i++){
list[i].setNumberOfYears(r.nextInt(30));
if (list[i].getNumberOfYears() > list[i+1].getNumberOfYears())
list[i] = list[i+1];
System.out.println(list[i].toString());
}
}
}
Thank you for looking!
Edit got rid of the irrelevant code
You set the number of years, but you never calculate the base, exponent or totalPay. That only happens in a constructor you never call.
What you need to do is move functional code out of the constructor and into a calculation method. That constructor should be for constructing the object.
old constructor:
public Loan(double anualInterestRate, int numberOfYears, double loanAmount) {
base = (double) (loanAmount * (1 + anualInterestRate / 12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
better way:
public Loan(double annualInterestRate, int numberOfYears, double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
}
public void calculatePay() {
base = (double) (loanAmount * (1 + annualInterestRate / 12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
Also, your method for sorting is flawed. You should decide what a good natural ordering for Loan is, then implement the Comparable interface.
Then you could use an existing sort library like this:
for (int i = 0; i < 9; i++) {
list[i].setNumberOfYears(r.nextInt(30));
list[i].calculatePay();
}
Arrays.sort(list);
for (Loan loan: list) {
System.out.println(loan);
}

Categories