I think I did it all correct however im having an error. Very confused.
Error: overtime.java:10: error: variable pay might not have been initialized
displayResults(pay);
Code:
import java.util.Scanner;
public class Overtime {
public static void main(String[] args) {
int hours;
double rate, pay;
Scanner in = new Scanner(System.in);
displayResults(pay);
System.out.println();
System.out.print( "Enter how many hours worked: " );
hours = in.nextInt();
System.out.print( "Enter hourly rate: " );
rate = in.nextDouble();
}
public double calculatePay( int hours, double rate, double pay ) {
if ( hours > 40 ) {
int extraHours = hours - 40;
pay = ( 40 * rate ) + ( extraHours * rate * 1.5);
} else
pay = hours * rate;
return pay;
}
public static void displayResults(double pay) {
System.out.printf( "\nGross Salary: %f", pay);
}
}
The code inside your main has to reordered:
public static void main(String[] args) {
int hours;
double rate, pay;
Scanner in = new Scanner(System.in);
System.out.print( "Enter how many hours worked: " );
hours = in.nextInt();
System.out.print( "Enter hourly rate: " );
rate = in.nextDouble();
pay = ;// call calculatePay here
displayResults(pay);
}
And you have to remove the pay parameter of the calculatePay method. Its declaration should be
public static double calculatePay( int hours, double rate )
The reason you get this error is the fact you didn't assign any value to variable payand you called a method displayResults() which needs this variable as an argument. Firstly you should calculate pay value with calculatePay (but you should delete double pay from list of arguments passed to this method, because there is no need to place it there).
After calculations made with calculatePay() and having its result in pay variable you can call displayResults() without problem.
Another problem is that calculatePay() need to made static and both your methods should be declared outside of the main() method body (the bold part of my answer is no longer relevant, because bad looking indentation made me a bit confused and I thought that methods were declared inside the main() method).
This looks a bit like a homework. So Iam providing only guidance:
Initialize all variables first and set them to values. (eg. double pay=1; ) and drop the Scanner.
Once this is working - add the Scanner and display all variables with System.out.format(...).
Once vars are displayed properly (point2) and (1)works - connect variables set by the Scanner with rest of your code
Good luck! :-)
Related
I'm trying to divide variables from pointsearned and creditsearned method in the pointsaverage method but it gives "Your grade point average isNaN" when i run it , how do i fix this ?(I'm a beginner)
public class JavaApplication40 {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
double credits = 0;
double Points = 0;
double average = 0;
IDnumber();
CreditsEarned(credits);
PointsEarned(Points);
System.out.println("Your grade point average is" + PointAverag(average, Points, credits));
}
public static void IDnumber(){
String docNuMBER;
System.out.println("Enter your student ID number ");
docNuMBER = keyboard.nextLine();
}
public static double CreditsEarned( double credits){
double NumCreditsEarned;
System.out.println("Enter your Credit hours earned");
NumCreditsEarned = keyboard.nextDouble();
return NumCreditsEarned;
}
public static double PointsEarned(double points){
double NumberOpoints;
System.out.println("Enter your credit points");
NumberOpoints = keyboard.nextDouble();
return NumberOpoints;
}
public static double PointAverag(double grade , double NumberOpoints ,
double NumCreditsEarned) {
double average ;
average = NumberOpoints/NumberOpoints;
return average ;
Here's what's happening in your program:
You set 'credits' and 'points' to 0.
These two variables have not been modified when you get to pass them to 'pointAverag'
System.out.println("Your grade point average is" + PointAverag(average, Points, credits));
this line, literally, does this:
System.out.println("Your grade point average is" + PointAverag(0, 0, 0));
And eventually leads to:
average = 0/0
in 'PointAverag' which is NAN when stored in a double.
Watch out for this line:
average = NumberOpoints/NumberOpoints;
it has logical mistake in it. It will always store either 1 or NAN.
As mentionned in the comments, you need to update those variables, 'credits' and 'points', by storing the returned value of your methods 'PointsEarned' and 'CreditsEarned' in them:
CreditsEarned(credits);
PointsEarned(Points);
Becomes
credits = CreditsEarned(credits);
points = PointsEarned(Points);
Hope this helps.
Write:
System.out.println("Your grade point average is" + PointAverag(IDnumber(), PointsEarned(Points), CreditsEarned(credits)));
instead.
If you don't use a returned value, it gets discarded.
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually, monthly, daily;
double balance;
int year = 10 ;
System.out.println("Enter the amount you will like to deposit or type exit to end.");
int deposit = key.nextInt();
annually = deposit * Math.pow((1 + rate/1),year);
monthly = deposit * Math.pow((1 + rate/12),year);
daily = deposit * Math.pow((1 + rate/365),year);
while (deposit)
{
}
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
This is what I currently have. What I am trying to accomplish is to make a loop to add the first outcome with the next one. Also make one formula instead of having three to find the annually, monthly and daily.
First and foremost, asking someone to write out your homework is really unethical, and not helpful for you in the long run. If you don't care about the long run, consider taking a different class. In a career scenario, you're expected to write code on your own.
Secondly, to actually answer your question, here are some tips:
It seems like you want to gather a value (deposit) from the user, and then calculate the Compound Interest for said value. Your program also needs to not exit until the user says to exit. i.e. they want to calculate the CI for a set of numbers.
First step is to check the value from the user. If it is a number, then do calculations on it. If it is a String, then check if it is "exit". In Java, this amounts to writing out an if-statement, and making use of the very helpful "instanceof" keyword. If you haven't learned about that, give this a read, or ask your teacher.
For the calculations part, you simply do calculations on the user's input while the input is not a string set to "exit".
Finally, print out your calculations.
That's it. Your code already has the calculation formulas down, so you just need to code the logic for handling user input.
import java.util.Scanner;
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How much money you want to deposit?");
int principle = sc.nextInt();
System.out.println("what is the rate you want?");
float rate = sc.nextFloat();
System.out.println("After how many years, you want to see your money?");
int year = sc.nextInt();
System.out.println("How many compounds in a year?");
int partialTime = sc.nextInt();
double b = year * partialTime;
double a = 1 + (rate/(partialTime*100));
double x = principle * (Math.pow(a,b));
System.out.println("Your interest in given time would be " + x);
}
}
A couple of suggestions - since you want to check user input against both String and int types, you could define a String type variable to hold the user input, and then do a try/catch to parse it as an Integer, if it's not an Integer check if the input equals "exit" (using the String.equals() method).
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually = 0, monthly = 0, daily = 0;
double balance;
int year = 10, deposit = 0 ;
String userinput = "";
do {
try {
System.out.println("Enter the amount you will like to deposit or type exit to end.");
userinput = key.nextLine();
deposit = Integer.parseInt(userinput);
}
catch (Exception e){
if (!userinput.equals("exit")){
System.out.println("Didn't recognize that input, please try again...");
}
else{
break;
}
}
} while (!userinput.equals("exit"));
annually += deposit * Math.pow((1 + rate/1),year);
monthly += deposit * Math.pow((1 + rate/12),year);
daily += deposit * Math.pow((1 + rate/365),year);
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
Depending on how you want the output, you can easily adjust the scope of the loop to display the amounts after each valid deposit input, or just once at the end, after the user enters "exit".
Hope this helps.
I am trying to do the calculations for the interest in another method, and I know that I have to make another method outside of main and then put return an the end, but I have no idea what to title this new method and how to go about doing the calculations there. I think it is the while loop that is confusing me. I have done this once before on a different project, so I have an idea of how to do it, but this project isn't anything like the other one and I don't really understand it. Any help is extremely appreciated as I have been working on this for a long time and just want to get it over with. Thanks in advance.
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
Based on your comment, I think you want this:
private static double addInterest(double S, double P, double i)
{
return S + (P * i);
}
...
public static void main()
{
...
while (timesLooped <= n)
{
S = addInterest(S, P, i);
}
EDIT
I made some small improvements just for fun:
I put the entire interest calculation into the function and used exponentiation rather than a loop.
I gave the variables more descriptive names.
I used System.out.format to print the result.
Here's the code:
private static double computeCompoundInterest(double principal, double rate,
double years) {
return principal * Math.pow(1 + rate, years);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("I am a savings account interest calculator.");
System.out.println("How much money have you deposited?");
double principal = scanner.nextDouble();
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
double rate = scanner.nextDouble();
System.out.println("How many years will you hold that money in the account?");
double years = scanner.nextDouble();
double total = computeCompoundInterest(principal, rate, years);
System.out.format("Your balance at the end of that period will be %.2f.\n", years, total);
}
I am having trouble with calling a method in the main of my program.
The program specifications are as follows:
setNoOfVehicles(): Returns the number of vehicles owned.
setWeeklyFuelCost(): Returns the average weekly cost of gas for all vehicles owned.
calcYearlyFuelCost(): Receives the average weekly fuel cost and returns the average annual fuel cost.
displayFuelCost(): Receives the number of vehicles owned, the average weekly fuel cost, and the average annual fuel cost.
main():
Calls setWeeklyFuelCost() and stores the returned value in a local variable.
Calls displayFuelCost() by sending it as arguments a call to setNoOfVehicles(), the local variable for the average weekly fuel cost, and a call to calcYearlyFuelCost().
Scanner is declared at the global level
public static void main(String[] args)
{
double x = setWeeklyFuelCost();
displayFuelCost( setNoOfVehicles(), x, calcYearlyFuelCost(x)); //This is the correct parameters I needed to pass thru displayFuelCost(). I didn't know this at the time and this is what I was trying to ask in this post.
}
private static int setNoOfVehicles()
{
System.out.print( "How many vehicles do I own? " );
int noOfVehicles = input.nextInt();
return noOfVehicles;
}
private static double setWeeklyFuelCost()
{
System.out.print( "Enter the average weekly fuel cost for my vehicles: ");
double weeklyFuelCost = input.nextDouble();
return weeklyFuelCost;
}
private static double calcYearlyFuelCost(double weeklyFuelCost)
{
double yearlyFuelCost = 0.0;
yearlyFuelCost = weeklyFuelCost * 52;
return yearlyFuelCost;
}
private static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost)
{
double difference = yearlyFuelCost - 5044.00;
if( yearlyFuelCost > 5044.00)
{
System.out.printf( "No of Vehicles: %d\n"
+ "Avg Weekly Fuel Cost: $%,.2f\n"
+ "Avg Annual Fuel Cost: $%,.2f\n\n"
+ "I am OVER budget by $%,.2f.", noOfVehicles, weeklyFuelCost, yearlyFuelCost, difference);
}
else if( yearlyFuelCost < 5044.00)
{
difference = difference * -1;
System.out.printf( "No of Vehicles: %d\n"
+ "Avg Weekly Fuel Cost: $%,.2f\n"
+ "Avg Annual Fuel Cost: $%,.2f\n\n"
+ "I am UNDER budget by $%,.2f. PAARRTY!!! ", noOfVehicles, weeklyFuelCost, yearlyFuelCost, difference);
}
else
{
System.out.printf( "No of Vehicles: %d\n"
+ "Avg Weekly Fuel Cost: $%,.2f\n"
+ "Avg Annual Fuel Cost: $%,.2f\n\n"
+ "I am RIGHT ON BUDGET!", noOfVehicles, weeklyFuelCost, yearlyFuelCost, difference);
}
}
}
The last specification is the one holding me up, call displayFuelCost()
My problem was that I didn't know exactly what parameters I needed to pass through displayFuelCost(). I knew I had to use the variable x above before asking this question.
displayFuelCost( setNoOfVehicles(), x, calcYearlyFuelCost(x)); was all that I needed to input to get the main to work correctly.
You call a method displayFuelCost() which is not defined in your class. Instead you have a method
private static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost) { ... }
that takes three parameters.
Change the method call to
displayFuelCost(1, 100.0, 5200.0); // sample values
to eliminate the error and get some result.
The code you pasted does not contain any class definition. If the main-method is in another class then the displayFuelCost-method, then you will have to change
private static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost)
to public :
public static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost)
That beeing said, I wouldn't recommend you this excessive usage of static methods. I don't see a reason why you shouldn't use proper object-oriented style (or at least a singleton-pattern, if it has to look static).
//EDIT:
The problem ist this part of your code:
public static void main(String[] args)
{
double x = setWeeklyFuelCost();
displayFuelCost(); //<-- need arguments here!
Inside your main function, you call the displayFuelCost-method, but do NOT provide the parameters it needs. When you have a look at the declaration of this method:
private static void displayFuelCost( int noOfVehicles, double weeklyFuelCost, double yearlyFuelCost)
}
You see that it needs 3 parameters: an integer, a double and another double. You have to provide them while calling the displayFuelCost function. For example like that:
public static void main(String[] args)
{
double x = setWeeklyFuelCost();
displayFuelCost(1, 2.5, 2.5); //<-- need parameters here!
}
//EDIT 2:
There are more problems in the whole code. I added an new answer concerning them.
Since I don't have the code of the scanner and the class I can not prove that my solution works, you have to try it out:
public class Test {
public static void main(String[] args) {
int vehicleNumber = setNoOfVehicles();
double costWeek = setWeeklyFuelCost();
double costYear = calcYearlyFuelCost(costWeek);
displayFuelCost(vehicleNumber, costWeek, costYear);
}
// rest of your code
}
But once again I have to warn you, that this is probably NOT what your teacher wants you to deliver. He wants a class that instantiates itself in the main method (e.g. Test test = new Test()) and than uses the instance-side methods (i.e. methods without static in the beginning) to fulfill the task. I would recommend you to try again. ;)
Can anybody tell me what I am doing wrong here. I need to calculate some values from user-input into some JOptionPane-input-dialog-boxes, then outputting the answers.
I would greatly appreciate any help I get. Thanks In Advance!
Input
Number of loans to compare (Could be more than 1)
Selling price
Down payment
You will ask the following for each loan they want to compare
Interest rate
Number of years
Processing
You will need to calculate the monthly payment for each scenario listed in part d for the given interest rates and number of years.
Output
Selling price
Down Payment
Loan Amount
List for each scenario
interest
years
payment
Here's my code so far:
package javamortgagecalculator;
import javax.swing.JOptionPane;
import java.util.*;
public class JavaMortgageCalculator {
public static void main(String[] args) {
//A. Enter the Number Of Loans to compare
String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
//Convert numberOfLoansString to int
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Selling Price of Home
String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
//Convert homeCostString to double
double sellingPrice = Double.parseDouble(sellingPriceString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
double downPayment = Double.parseDouble(downPaymentString);
//Get the loanAmount by Subtracting the Down Payment from homeCost
double loanAmount = sellingPrice - downPayment;
//D. Ask the following for as many number of loans they wish to compare
//D1 Get the interest rate
double[] annualInterestRatesArray = new double[numberOfLoans];
double[] monthlyInterestRateArray = new double[numberOfLoans];
int[] numberOfYearsArray = new int[numberOfLoans];
double[] monthlyPaymentArray = new double[numberOfLoans];
double[] totalPaymentArray = new double[numberOfLoans];
int counter = 1;
for (int i=0; i < numberOfLoans; i++)
{
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
double annualInterestRate = Double.parseDouble(annualInterestRateString);
annualInterestRatesArray[i] = (annualInterestRate);
//Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
monthlyInterestRateArray[i] = (monthlyInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
int numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArray[i] = (numberOfYears);
//Calculate monthly payment
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPaymentArray[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPaymentArray[i] * numberOfYears * 12;
//Format to keep totalPayment two digits after the decimal point
totalPayment = (int)(totalPayment * 100) / 100.0;
totalPaymentArray[i] = (totalPayment);
counter++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numberOfLoans; i++) {
sb.append(String.format("\t \t \t \t \t \n", sellingPrice, downPayment, loanAmount, Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray)));
}
String toDisplay=sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
If I was forced, presumably by a large green, and particularly ugly troll masquerading as a programming teacher, to use multiple JOption panes for input and output then here's how I'd tackle the problem. This is meant for your information only... if you hand this in as your own work your teacher will smell a rat, and trolls have google too.
package forums;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/**
* Compares total cost of mortgages (aka ordinary annuity certains)
*/
public class MortgageCalculator
{
public static void main(String[] args)
{
// 1. input
final double price = Enter.aDouble("the purchase of the property");
final double deposit = Enter.aDouble("down payment");
Loan.setPrinciple(price - deposit);
int numLoans = Enter.anInteger("number of loans to compare");
Loan[] loans = new Loan[numLoans];
for ( int i=0; i<numLoans; ++i ) {
loans[i] = new Loan(
Enter.aDouble("Annual interest rate for Loan " + (i+1) + " (eg: 6.75)") / 100.0 / 12.0
, Enter.anInteger("number of years for Loan " + (i+1) + " (eg 20)") * 12
);
}
// 3. Output
final String caption =
"Principle " + Format.money(Loan.getPrinciple())
+ " = Price " + Format.money(price)
+ " - Deposit " + Format.money(deposit);
StringBuilder results = new StringBuilder(64 + numLoans * 64);
results.append("Monthly Rate, Months, Monthly Repayment, Total Repayments\n");
for ( Loan l : loans ) {
results.append(String.format("%5s, %d, %13s, %13s\n"
, Format.percent(l.rate)
, l.periods
, Format.money(l.payment())
, Format.money(l.totalPayment())
));
}
JOptionPane.showMessageDialog(null, results.toString(), caption, JOptionPane.INFORMATION_MESSAGE);
}
static class Format
{
static java.text.Format MONEY = new DecimalFormat("$#,###.##");
static String money(double amount) {
return MONEY.format(amount);
}
static java.text.Format PERCENT = new DecimalFormat("0.###%");
static String percent(double amount) {
return PERCENT.format(amount);
}
static StringBuilder join(String between, Object... values) {
StringBuilder result = new StringBuilder(values.length * 16);
if ( values.length > 0 ) {
result.append(values[0].toString());
for ( int i=1; i<values.length; ++i ) {
result.append(between)
.append(values[i].toString());
}
}
return result;
}
} // end class Format
static class Enter
{
public static int anInteger(String fieldDesc) {
return Integer.parseInt(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
}
public static double aDouble(String fieldDesc) {
return Double.parseDouble(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
}
} // end class Enter
} // end class MortgageCalculator
class Loan
{
private static double principle = 34324.121221312432;
final double rate;
final int periods;
static void setPrinciple(double principle) {
if (Loan.principle != 34324.121221312432)
throw new ReadOnlyException("The Principle can't be changed once set.");
Loan.principle = principle;
}
static double getPrinciple() {
return Loan.principle;
}
/**
* Initialises a new loan objects
* #param double rate The interest rate per period, as a percentage.
* eg: 0.00625 is 7.5% per annum.
* #param int periods The number of periods of the loan, typically months.
*/
Loan(double rate, int periods) {
this.rate = rate;
this.periods = periods;
}
// 2. processing
double payment() {
return principle * rate / (1 - 1/Math.pow(1+rate,periods) );
}
double totalPayment() {
return periods * payment();
}
}
class ReadOnlyException extends RuntimeException
{
private static final long serialVersionUID = 0L;
public ReadOnlyException(String message) {
super(message);
}
}
The "list of loans to compare" is represented by an array of Loan objects... I.e: each "loan option" is represented by an instance of the Loan class, which groups all the attributes of a particular loan into one nice tidy "thing" which we can then manipulate as a whole. This a better appraoch than the technique you're using to store loan attributes, which is called "parallel arrays"... and well, umm, it's a bit outdated, in-fact it's got a (greasy) mullet, it's wearing a (too tight) orange safari suit with a (safron pink) head-band... It wasn't a good look in the eighties, and these days, well it's likely to get you beaten-up, arrested, or both; depending on your locale... Basically: We have have better ways now!
The Loan class also has a couple of handy "calculated fields" to do the computations for us. This means that if the WAY we calculate repayments changes for some reason in future, we only have one place to change it, and everything that uses Loans (which could be reading, writing, permuting, totalling, repossessing, or even wholesaling loans) does NOT have to change... they just pick up the change "for free".
In this contrived use-case all our Loans will be for the same ammount, only the interest rates and periods vary... so the Loan class also has a static variable called "principle", which holds THE "common" principle for ALL instances of the Loan class. The principle may only be set once. Any subsequent attempt to set the prinicple will cause a ReadOnlyException to be thrown.
Anyway, I hope that you learn something from seeing another way to tackle some of the sub-problems you may have dicovered while doing this exercise yourself. One tip for the future: Grab your class-mates code for this exercise and read through it... you can learn a LOT from how other people tackle things.
Cheers. Keith.
Now you need to examine the result returned by showMessageDialog(), as shown here.
String.format("\t \t \t \t \t \n", sellingPrice, ...
That's just going to output 5 tabs. You want
String.format("%s %s %s %s %s %n", sellingPrice, ...
for (int i = 0; i < numberOfLoans; i++)
{
sb.append(/*...snip...*/ Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray));
}
You haven't told us what the problem is, but I don't think this bit is doing what you want. You're asking the program to print out the entirety of your three arrays every time the loop goes round. Instead, you probably want to access the specific array element for each loan, right? Something like...
for (int i = 0; i < numberOfLoans; i++)
{
sb.append(/*...snip...*/ annualInterestRatesArray[i], numberOfYearsArray[i], monthlyPaymentArray[i]);
}
Your JOptionPane.showMessageDialog(null... is inside a for loop. So it will show it as many times as the value of numberOfLoans2 . If you dont want that, move your
String toDisplay = sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
outside the for-loop.
In your answer printing method the numberOfLoans2 variable is used in two places: in a for loop making the printing happen many times (outer loop) and in a for loop making the mathematic calculation (inner loop). Probably the outer one is with no use, so remove it and the result may be shown once. Remember to remove the ending } on the end of the loop element to keep the structure ok :)