More Than One Java Input - java

I am sort of a Newbie to this forum and to Java. I am having a difficult time trying to find a way to ask the user to enter more than one loan to compare from steps D down. I need to be able to ask the user for a different interest rate and number of years for the amount they entered in step A. So if they entered 10 then I would have to ask them 10 times for an interest rate and years and output it in a table format using tabs. Any help is much appreciated. Thanks in advance.
Edit: Thank you so much for your help! I updated the code.
//A. Enter the Number Of Loans to compare
String numberOfLoansString = JOptionPane.showInputDialog("Enter the amount of loans to compare:");
//Convert numberOfLoansString to int
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Amount/Selling Price of Home
String loanAmountString = JOptionPane.showInputDialog("Enter the loan amount:");
//Convert loanAmountString to double
double loanAmount = Double.parseDouble(loanAmountString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home:");
double downPayment = Double.parseDouble(downPaymentString);
//D. Ask the following for as many number of loans they wish to compare
//D1 Get the interest rate
double[] anualInterestRatesArray = new double[numberOfLoans];
double[] monthlyInterestRateArray = new double[numberOfLoans];
int[] numberOfYearsArray = new int[numberOfLoans];
double[] monthlyPaymentArray = new double[numberOfLoans];
double[] totalPaymentArray = new double[numberOfLoans];
for (int i=0; i < numberOfLoans; i++)
{
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate:");
double annualInterestRate = Double.parseDouble(annualInterestRateString);
anualInterestRatesArray[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:");
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);
}

You need to do all the repeated processing logic inside a loop such as for( ... ) loop. Use an array to store different values for the number of loans.

Use for loops for this.
P.S : You can use other loops [while, do-while] as well.

An example for using for loop
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//section of code which shouldnt be repeated here outside the loop.
for( int i = 0; i < numberOfLoans ; i++ )
{
//Write Step D here , because you want it to be repeated
}

You probably need to use arrays and loops. Use arrays to store all the values entered and a loop to get the values.
double[] anualInterestRates = new double[numberOfLoans];
double[] monthlyInterestRates = new double[numberOfLoans];
int[] numberOfyears = new int[numberOfLoans];
Then you can loop and ask for each loan values:
for(int i= 0; i < numberOfLoans; i++){
//get the anual interest rate
anualInterestRates[i] = the anual interets rate gotten
//etc
}
Now you have 3 arrays of values. You can use a second loop to calculate the output and display.

Related

Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. I also need to include a while loop to make sure the cashier is given an amount greater than the amount due.
I have the following so far, but don't know where to go from here:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
Use the mod operator and division to find values at each step
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
please note that casting the result of a division to an integer will truncate the returned value to a whole number.

Nickles in Coin Counter not displaying correct amount

I was just given my first assignment in my Java class, and we were tasked with creating a program that counts nickles and displays the total amount of money. However, whenever I put an odd number of nickles it does not display the corrent amount of money. For example, 1 nickles turns into $.5 instead of $.05. 21 Nickles turns into $1.5 instead of $1.05. I'm asumming this is an easy fix for an easy problem, but I am finding myself stumped. Thanks for the help.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
int nickles5 = nickles * 5;
int dollars = nickles5 / 100;
int change = nickles5 % 100;
System.out.println("You have $" + dollars + "." + change);
}
I'll go out on a limb here, to try to solve your problem. It appears that you will ask the user to enter some number of nickels, and you will output the amount in dollars. Please let me know if this is incorrect in any way.
Now look at the following code.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
double nickles5 = nickles * 0.05;
System.out.println("You have $" + nickles5);
}
After we have the number of nickels stored in an int, we multiply it by 0.05, to get the actual value of all the nickels. We store this in a double variable [Note: int multiplied to a double, returns a double; it is called numeric promotion]. Now, to get the total value, you can simply print this double variable. In a case where n=2, nickels5 = 0.1. So, it will print $0.1
If you want this to show up as $0.10, simply replace the nickels5 with String.format( "%.2f", nickels5)
Now your final line will look like:
System.out.println("You have $" + String.format( "%.2f", nickels5));
Let me know if this solved your issue.
You need to format change to use 2 digits, rather than just printing out the raw number. Specifically, if change==5, you want to print out 05.
You can do this with String.format("%02d", change)
You have a random apostrophe at the end, why?
You want to use floats instead of ints, like this:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
System.out.println("$"+ amount);
Output:
Deposit your Nickles.
1
$0.05
Deposit your Nickles.
21
$1.05
EDIT: Code with formatted output:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
String output = String.format("%02f", amount);//f(loat) not d
System.out.println("$"+ output);

Loan calculator compound interest java

double a = Double.parseDouble(amount.getText());
double r = Double.parseDouble(rate.getText())/100;
double y = Double.parseDouble(years.getText());
double m=y*12;
double simple =a+(a*r*y);
double compound = a * Math.pow(1+ r, m);
String d = String.format("%.2f", simple);
String d1 = String.format("%.2f", simple/12);
String d2 = String.format("%.2f", compound);
int x=1;
while(x<=m && type.getSelectedItem().equals("Simple")) {
monthly1.append(String.valueOf(x+(". ")+d1+("\n")));
x++;
total1.setText(String.valueOf(d));
}
if (type.getSelectedItem().equals("Compound")){
for (int month=1;month<=m;month++){
monthly2.append(String.valueOf(month+(". ")+d2+"\n"));
total2.setText(String.valueOf(d2));
}
}
Simple interest works fine but compound monthly doesn't. I tried
amount:1000 rate:5 years 3.
And got
1. 5791.82
2. 5791.82
3. 5791.82
up to 60.
And I want it to show how much I have to pay monthly.
You only seem to calculate compound once, at the very beginning of your code. I'd create a method calculateCompoundInterest(int month) and then call this from within your loop like so:
for (int month=1; month <= m; month++) {
String monthlyAmount = String.format("%.2f", calculateCompoundInterest(month));
monthly2.append(String.valueOf(month+(". ")+monthlyAmount+"\n"));
total2.setText(String.valueOf(d2));
}
You are calculating monthly interest incorrectly.
formula a* Math.pow(1+r,y) needs to be applied like a* Math.pow(1+r/12,y*12) if compounded monthly. you need to convert your rate as well to use in the formula.
Please see this for more explanation of formula.
Here is the code to help you started:
for (int month=1;month<=m;month++){
d2 = String.format("%.2f",a * Math.pow(1+ r/12, month));
monthly2.append(String.valueOf(month+(". ")+d2+"\n"));
total2.setText(String.valueOf(d2));
}

Beginner Loop GUI

I have to make this GUI that is a CD calculator.
I put in the Initial investment ($): e.g. 2000
the Annual interest rate (%): e.g. (8%)
Ending value ($): e.g. 5000
The program then outputs on a jLabel: The amount of years required are "12" (e.g.)
I need to make a do while loop and a counter.
I did the get text from the 3 text fields then add the initialInvestment with the annual rate % but having trouble with the loop and the counter?
int initialInvestment, endValue, cdvalue;
double cdValue, annualDecimalConvert, annualRate;
initialInvestment = Integer.parseInt(initialInvestmentInput.getText());
annualRate = Double.parseDouble(interestRateInput.getText())/100;
endValue = Integer.parseInt(endingValueInput.getText());
cdValue = initialInvestment + (initialInvestment * annualRate);
double a = cdValue;
while (a <= endValue){
a = a++;
yearsOutput.setText("The required year needed is: " + a);
}
You're simply adding 1 to a every iteration of the loop. So it'll take a few thousand iterations that way to fullfil the loop requirements.
What you have to do is keep adding the interest every year while keeping count of the years and only update the output after you're done looping.
int initialInvestment, endValue;
double cdValue, annualDecimalConvert, annualRate;
initialInvestment = Integer.parseInt(initialInvestmentInput.getText());
annualRate = Double.parseDouble(interestRateInput.getText())/100;
endValue = Integer.parseInt(endingValueInput.getText());
// First year interest is counted here.
cdValue = initialInvestment + (initialInvestment * annualRate);
int years = 1;
while (cdValue < endValue){
cdValue = cdValue + (cdValue * annualRate);
years++;
}
yearsOutput.setText("The required year needed is: " + years);

determine the periodic loan payment

am not getting this program to display my instalments correctly can I please get some help thanks......
package Loops;
import java.util.Scanner;
/**
*
*
*/
public class program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//variabled decleared
double rate;
double payment;
//input
System.out.print("Enter Loan Amount:");
double principal = input.nextDouble();
System.out.print("Enter Annual Interest:");
double interest = input.nextDouble();
System.out.print("Total payments per year:");//12=monthly,4= quartely,2=semi-annually and 1=annually
double period = input.nextDouble();
System.out.print("Enter Loan Length :");
int length = input.nextInt();
//proces
double n = period * length;
rate = interest / 100;
double monthly_rate = rate / period;
payment = principal * (principal * (monthly_rate * Math.pow((1 + monthly_rate), n)));
System.out.printf("Your Monthly sum is %.2f", payment);
}
}
principal = 50000; //Redacted. Eating my words.
period = 4;
length = 4;
n = 16;
rate = 0.085;
monthly_rate = 0.085 / 16 = 0.0053125;
payment = 50000 * 50000 * 0.0053125 * (1 + 0.0053125) ^ 16;
= 2.5x10^9 * 0.0053125 * 1.088;
= Something remainingly massive
Basically... your formula is wrong. Wouldn't you need to divide by the power quotient? Where is your source on that formula?
payment = principal * (rate + (rate / ( Math.pow(1 + rate, n) - 1) ) );
Source
Example:
payment = 50000*(0.085+(0.085/(1.085^16-1)))
= 5830.68
Try this for your formula:
//this is how much a monthly payment is
payment = (rate + (rate / ((Math.pow(1 + rate), n) -1)) * principal
This is based off one of the first google results for the formula. Please post the results and expected answer if it is wrong.
I'm pretty sure your formula is just off, as you stated above that there should be a denominator in the equation.
You can use r* Math.pow ((1+r),n) to calculate the numerator and part of the denominator

Categories

Resources