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);
Related
So I am working on this homework problem called "pennies for pay" and I am basically done except for one issue. My for loop prints out the number of the inputted number that many times if that makes sense?
public class Assignment3 {
public static void main(String[] args) {
//INITIAL VARIABLES
int workdays;
double money;
double total = 0;
double add;
//GATHERING NUMBER OF DAYS WORKED
System.out.println("For how many days will the pay double? ");
Scanner a = new Scanner(System.in);
workdays = a.nextInt();
//PARTIAL OUTPUT
System.out.println("Day\t\tTotal Pay");
System.out.println("__________________________");
//FOR LOOP
for(int payday = 1; payday <= workdays;payday++){
money = Math.pow(2,payday - 1);
System.out.println(workdays +"\t$\t"+ money/100);
total = total + money/100;
}
//MORE OUTPUT
System.out.println("__________________________");
System.out.println("Total\t$\t" + total );
}
}
When I input 12 for days, the number 12 repeats itself 12 times. how can I get it to go from 1-12 please and thank you.
In your for loop you are printing the variable workdays in which it's value doesn't change inside the loop, that means it's constant.Since your target is to output pennies per day you should try this code if it helps
for(int payday = 1; payday <= workdays; payday++){
money = Math.pow(2,payday - 1);
System.out.println(payday + "\t$\t" + money/100);
total += money/100;
}
The value of workdays variable is always 12 if you input 12. In your System.out.println inside the loop, use payday instead of workdays. Because payday is the one being incremented for each iteration.
That should fix it.
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Whenever I execute the program the average change always is 0 and I do not understand why.
/*LuckySevens.java
Simulate the game of lucky sevens until all funds are depleted.
1) Rules:
roll two dice
if the sum equals 7, win $4, else lose $1
2) The inputs are:
the amount of money the user is prepared to lose
3) Computations:
use the random number generator to simulate rolling the dice
loop until the funds are depleted
count the number of rolls
keep track of the maximum amount
4) The outputs are:
the number of rolls it takes to deplete the funds
the maximum amount
the average net change after 100 rolls
*/
import java.util.Scanner;
import java.util.Random;
public class LuckySevens {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
Random generator = new Random();
int die1, die2, // two dice
dollars, // initial number of dollars (input)
countAtMax, // count when the maximum is achieved
count, // number of rolls to reach depletion
maxDollars, // maximum amount held by the gambler
averageWin, // the average net change after 100 rolls
initialDollars; // initial amount of money user has
// Request the input
System.out.print("How many dollars do you have? ");
dollars = reader.nextInt();
// Initialize variables
maxDollars = dollars;
initialDollars = dollars;
countAtMax = 0;
count = 0;
// Loop until the money is gone
while (dollars > 0){
count++;
// Roll the dice.
die1 = generator.nextInt (6) + 1; // 1-6
die2 = generator.nextInt (6) + 1; // 1-6
// Calculate the winnings or losses
if (die1 + die2 == 7)
dollars += 4;
else
dollars -= 1;
// If this is a new maximum, remember it
if (dollars > maxDollars){
maxDollars = dollars;
countAtMax = count;
}
/* TODO:FIX BELOW STATEMENT
it always returns influx as 0 */
if (count == 100) {
averageWin = ((maxDollars - initialDollars) / 100);
System.out.println ("In the first 100 rolls there an average money influx of " + averageWin + " per roll.") ;
}
}
// Display the results
System.out.println
("You went broke after " + count + " rolls.\n" +
"You should have quit after " + countAtMax +
" rolls when you had $" + maxDollars + ".");
}
}
Make averageWin as double variable.
Change calculation of average win as below
averageWin = ((double)maxDollars - (double)initialDollars) / 100;
I tried the following to get the correct answer.
Changed type of averageWin
double averageWin;
And then calculation formula to
averageWin = (maxDollars - dollars) / 100.0;
This will preserve the precision and give you the correct answer.
I want to start off saying that I'm new at this. I'm trying to make a for loop that will Show me the different 40 yard dash times converted into MPH. The problem is output that's being shown:
5.96 40 Time is 13.727882855399633 Miles Per Hour
6.96 40 Time is 11.755485893416928 Miles Per Hour
7.96 40 Time is 10.27866605756053 Miles Per Hour
I want it to show as 5.96, 5.97, 5.98, etc instead of 5.96 and 6.96.
Does anyone understand what I'm trying to do as well as to fix this problem I'm having?
public class FortyToMPH {
public static void main (String args []) {
double yards, foot, FeetInMiles, SecondsPerHour,FeetLength;
double FortyTime, Minutes, SecondsPerMile, MPH;
int counter;
counter = 0;
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime++) {
yards = 40; // length in yards
foot = yards * 3; // convert to feet
System.out.println();
FeetInMiles = 5280; // The number of feet in a Mile
SecondsPerHour = 3600;
FeetLength = FeetInMiles / foot; // You divide the Feet in Miles by the feet conversion of 40 yards
System.out.println();
SecondsPerMile = FeetLength * FortyTime;
MPH = SecondsPerHour / SecondsPerMile;
System.out.println(FortyTime + " 40 Time is " + MPH + " Miles Per Hour ");
counter++;
// every 10th line, print a blank line
if(counter == 10) {
System.out.println();
counter = 0; // reset the line counter
}
}
}
}
The problem is that you're using the ++ operator in your for loop definition:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime++) {
Change the for loop to a while loop that includes a line incrementing FortyTime by 0.01 each loop:
while(FortyTime <= 7.99) {
FortyTime += 0.01;
// execute the rest of your code here
}
MarounMaroun rightfully pointed out that using a double as a loop counter runs the risk of nasty floating-point arithmetic errors, so I've changed the for loop to a while loop.
The ++ operator means "reassign the value of x as x + 1." It'll only give you increments (or decrements, with --) of 1.
Note that this is going to print out hundreds of lines before it completes.
I would recommend you to use int in your loop and perform all calculations of doubles inside the loop to prevent problems with floating point arithmetic:
for(int i = 0; i < something; i++) {
double fortyTime = 4.96 + i;
//...
}
Also please pay attention to Java Naming Conventions and rename your variables.
To demonstrate problems of floating point arithmetic, try this loop:
for(double i = 0; i < 1.0; i += 0.1)
System.out.println(i);
This will print
0.0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
And you don't want output like this in your program.
Here I modified the code you gave to print doubles as a two decimal place numbers (see format %.2f) produced in the loop while (the step for the loop is defined in DELTA variable).
public class FortyToMPH
{
public static void main (String args [])
{
double yards, foot, feetLength;
double fortyTime = 4.96, minutes, secondsPerMile, mph;
int counter = 0;
/**
* Constants.
*/
final double FEET_IN_MILES = 5280;
final double SECONDS_PER_HOUR = 3600;
final double DELTA = 0.01;
final double END = 7.99;
while (fortyTime <= END)
{
yards = 40; // length in yards
foot = yards * 3; // convert to feet
feetLength = FEET_IN_MILES / foot; // You divide the Feet in Miles by the feet conversion of 40 yards
secondsPerMile = feetLength * fortyTime;
mph = SECONDS_PER_HOUR / secondsPerMile;
System.out.format("%.2f 40 Time is %.2f Miles Per Hour%n", fortyTime, mph);
counter++;
// every 10th line, print a blank line
if(counter == 10) {
System.out.println();
counter = 0; // reset the line counter
}
fortyTime += DELTA;
}
}
}
just change the for loop like this:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime=FortyTime+.01)
and print it like
System.out.println((float)FortyTime + " 40 Time is " + MPH + " Miles Per Hour ");
You need to make two changes:
for(FortyTime = 4.96; FortyTime <= 7.99; FortyTime=FortyTime+0.01)
So that the FortyTime is incremented by 0.01 and not 1 and
System.out.printf("%.2f 40 Time is %f Miles Per Hour ", FortyTime, MPH);
So that it prints in correct precision.
I am attempting a previous years exam paper in preparation for my own exam.
The question is as follows:
Write a method to calculate and return the value of an investment in n years at the interest rate 7% a year. The method should have a real output type and two parameters, double invest and int n.
I am able to produce the required variables and implement them either in a while loop or a for loop but I am unsure how to actually capture the first year investment total (1070), store it and actually add this to the following year investment total, and then so on?
I just require some pointers please in how to capture the first year total, then add to the second year, then the third year etc.
Here is my code:
public class Investment {
public static void main(String[] args) {
double investment = 1000;
double interest = investment * 0.07;
double balance = interest + investment;
int years = 5;
int count = 0;
for (int i = 0; i < years; i++) {
double totalBalance = balance + balance;
count++;
System.out.println("Your investment is: " + totalBalance
+ ". Years invested: " + count);
}
}
}
Please forgive any errors in my code. I am still learning the Java syntax.
Thank you.
do you really need loop?
how about :
balance = invest * Math.pow(1.07, n)
also you may want to use BigDecimal type instead of double to do currency calculation.
EDIT
(get the investment growth every year.)
I just read the exam question you quoted. it asked for a total balance, I therefor posted that line. if you need to get the growth data each year, you could write a loop, e.g.:
for(int i=1;i<=n;i++)
System.out.println(invest*0.7*Math.pow(1.07,i-1));
(codes are not written in IDE, could have typoes)