I have a project where I have to write a program that prompts the user for an initial investment amount and a goal investment amount and calculate how many years it will take to grow from the initial amount to the goal amount with a fixed interest rate (ie: 5 %). (use the WHILE loop). Print out the results from each year. For example, if you chose to invest $1,000 for 5 years:
Year 1 1005
Year 2 1011
Etc:
I was able to compile the java program but I was only able to prompt the user for an initial investment and goal investment with a 5% interest. The output was incorrect. What am I doing incorrect? Here is my code.
import static java.lang.System.out;
import java.util.Scanner;
import java.io.*;
public class Investment_Calculator {//main
public static void main(String[] args) {//begins body
double principal = 1;//initial amount investing
double interest = 1;
double rate = 0.05;//the fixed interest amount
int years = 1;//amout of years it will take to achieve goal
double goal = 1;
double total = 1;
Scanner myScanner = new Scanner(System.in);
System.out.println("*************************************** ");
System.out.println("* Welcome to the Investment Calculator * ");
System.out.println("*************************************** ");
System.out.println ("Enter your initial investment amount: if you want to exit enter 0.");
int inputNumber = myScanner.nextInt();
principal = inputNumber;
if (inputNumber == 0){//if num = 0 exit class
System.exit(0);
}
System.out.println ("Enter your goal investment amount: ");
int inputNumber2 = myScanner.nextInt ();
goal = inputNumber2;
System.out.println ("The fixed interest rate is 5%");
total= principal; // start with our initial amount of money
for (; total < goal; total= (1+interest)*total);
{ System.out.print("The number of years you must invest to meet your goal of $ ");
System.out.print(goal);
System.out.print(" is");
System.out.println(years);
System.out.println(" years");
}
}
}
for (; total < goal; total= (1+interest)*total);
You have a semi-colon at the end of this loop. Remove it.
Because of that, your next set of print statements after for loop becomes an unnamed block: -
{
System.out.print("The number of years you must invest to meet your goal of $ ");
System.out.print(goal);
System.out.print(" is");
System.out.println(years);
System.out.println(" years");
years++; <-- // Increment `years` here.
}
And those will be executed only once.
UPDATE: -
You can use the below code to get the totalInterest for each year and the final output
int years = 1;
while (principal <= goal) {
double totalInterest = principal * rate * years / 100.0;
principal = principal + totalInterest;
System.out.println("Interest amount for year: " + years +
" = " + totalInterest);
years++;
}
System.out.print("The number of years you must invest to meet your goal of $ ");
System.out.print(goal);
System.out.print(" is");
System.out.println(years);
System.out.println(" years");
The semicolon at for(; total < goal; total = (1+interest) * total); is causing problems.
change it to :
for (; total < goal; total= (1+interest)*total)
{
System.out.print("The number of years you must invest to meet your goal of $ ");
System.out.print(goal);
System.out.print(" is");
System.out.print(years);
System.out.println(" years");
}
Replace this with your current for- statement
int year = 0;
for (; total < goal; total= ((1+rate)*total), ++year)
{
...
// whatever you were doing in for loop
}
System.out.println (year);
Related
I am a beginner coder using Netbeans Java. I have created a code that initially asks how many gallons are in your gas tank. Then, it will have a while loop asking how many miles you will be traveling for this first run and how fast are you traveling. This will repeat with a while loop until you input '0' to stop adding trips. I am stumped on how to convert this while loop into only using For loops. I would greatly appreciate the assistance. Here is my code that has while loops.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int tank;
double miles;
double speed;
double totalMiles = 0.0;
int choice;
double time;
double totalTime = 0.0;
double fuelConsumption;
System.out.print("How many gallons of gas is in your tank (Integer 1-15)? ");
tank = input.nextInt();
System.out.printf("%s%d%s\n\n" , "You have ", tank , " gallons of gas in your tank.");
System.out.print("Are you going on a trip (1 = Yes or 0 = No)? ");
choice = input.nextInt();
while (choice == 1)
{
System.out.print("How many miles are you traveling? "); // miles
miles = input.nextFloat();
System.out.print("What is your speed for this run (MPH)? "); // speed
speed = input.nextInt();
System.out.print("\n");
totalMiles = totalMiles + miles;
time = (miles/speed);
totalTime += (time*60);
fuelConsumption = (20*(tank/totalMiles));
System.out.print("Is there another leg in your trip (1 = Yes or 0 = No)? "); // asking another leg
choice = input.nextInt();
if (choice == 0)
{
System.out.printf("%s%5.2f%s\n","Your data for this trip is: \n"
+ "You traveled a total of about ", totalMiles , " miles.");
System.out.printf("%s%.2f%s\n" , "You traveled about " , totalTime , " minutes.");
if (fuelConsumption >= 2)
{
System.out.println("Your car has enough gas to return.");
break;
}
else
{
System.out.println("Your car will need more gas to return.");
break;
}
}
}
}
}
That is not a use case for a for loop, where we iterate over a known number of elements for do a known number of iterations. Like, repeat 10 times or such.
Technically it can be solved with a for loop, but that is abusing the concept a bit. The while loop is a perfect fit for that task.
This is not a place to use a for-loop, you use a for loop for something like this:
printAmount = 10;
for (int i = 0; i < printAmount; i++) {
System.out.println("Hello World");
}
Here you are using the for loop to print "Hi" for the amount in printAmount.
Your case is different: You want the while-loop to repeat while the input is "1" so you use a WHILE-loop.
I am working on a program for an assignment.
There I got stuck on how to add the days and months for my program.
I can already convert the simple interest into years, but not for months and days:
import java.util.Scanner;
public class SimpleInterest {
public static void main(String[] args) {
double PAmount, ROI, TimePeriod, simpleInterset;
Scanner scanner = new Scanner(System.in);
System.out.print(" Please Enter the Principal Amount : ");
PAmount = scanner.nextDouble();
System.out.print(" Please Enter the Rate Of Interest : ");
ROI = scanner.nextDouble();
System.out.print(" Please Enter the Time Period in Years : ");
TimePeriod = scanner.nextDouble();
simpleInterset = (PAmount * ROI * TimePeriod) / 100;
System.out.println("\n The Simple Interest for Principal Amount " + PAmount + " is = " +
simpleInterset);
}
}
Just ask them separatly then compute the global time
System.out.print(" Please Enter the Principal Amount : ");
double pAmount = Double.parseDouble(scanner.nextLine());
System.out.print(" Please Enter the Rate Of Interest : ");
double rOI = Double.parseDouble(scanner.nextLine());
System.out.print(" Please Enter the Time Period in Years : ");
double years = Double.parseDouble(scanner.nextLine());
System.out.print("And months : ");
double months = Double.parseDouble(scanner.nextLine());
System.out.print("And days");
double days = Double.parseDouble(scanner.nextLine());
double timePeriod = years * months / 12 + days / 365;
double simpleInterset = (pAmount * rOI * timePeriod) / 100;
System.out.println("\n The Simple Interest for Principal Amount " + pAmount + " is = " + simpleInterset);
I'd suggest :
don't define variable before using it if you don't need to do so
use nextLine and parse what you need, you'll avoid suprise with return char
as Java convention, use lowerCamelCase to name your variables
This question already has answers here:
Java: Literal percent sign in printf statement
(4 answers)
Closed 7 years ago.
How do I print a % sign in Java? I have tried "\%", which doesn't seem to work. Any ideas?
Bellow is the code corrected, as mentioned above you should use double % to escape %, i.e: %%
I have also added some new line characters to make the app look more neat.
import java.util.Scanner;
public class test
{
public static void main(String args[])
{
//A Simple Averaging Program
Scanner input = new Scanner(System.in);
//Declare variables:
double total = 0;
double counter = 0;
long mark;
double average;
int numOfPupils;
int totalMarks;
//Ask how many papers the teacher would like to average:
System.out.println("How many student's papers would you like to avarage?");
numOfPupils = input.nextInt();
//Ask how many marks were available to the student to earn:
System.out.println("How many marks were available to the student?");
totalMarks = input.nextInt();
//Repeat the amount of papers times:
while (counter < numOfPupils)
{
//Ask how many marks the student got:
System.out.printf("\nHow many marks did student number %s get? \nStudent %s scored: ", counter + 1, counter + 1);
mark = input.nextLong();
total += mark;
System.out.printf("Student %s scored: %s%%", counter + 1, ((100 / totalMarks) * mark));
counter++;
}
average = total / (counter);
System.out.printf("\nThe average was %s marks.", average);
input.close();
}
}
Off-topic but may need consideration, is that your code will fail in some cases, as you need to handle some invalid inputs.
Im trying to write a code, that computes CD value, for every month.
Suppose you put 10,000 dollars into a CD with an annual percentage yield of 6,15%.
After one month the CD is worth:
10000 + 10000 * 6,15 / 1200 = 10051.25
After the next month :
10051.25 + 10051.25 * 6,15 / 1200 = 10102.76
Now I need to display all the results for the specific number of months entered by the user,
So
month1 =
month2 =
But whth this code I wrote, nothing is printed.
Can you see what's wrong?
Thanks in advance!
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
while (i != months) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
You do not modify neither i nor months in
while (i != months) {
....
}
so if the (i != months) condition is satisfied, the loop runs forever, and you never get to System.out.print statement.
for (int i = 1; i < months; i++) {
while (i != months) {
//you have to modify i or to modify the while condition.
}
if you don't modify i in the while you can't exit from the loop
Corrected code-
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextInt();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i <= months; i++)
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
}
Note: If you want to print values for each month then the print statement should be inside the loop. You don't need two loops for the objective that you have mentioned above.
As you have been told your code won't get out of the while loop if you don't modify it. Simply remove the while loop. Your code should be like this:
import java.util.Scanner;
public class CDValue {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter an amount");
double amount = input.nextDouble();
System.out.println ("Enter the annual percentage yield");
double percentage = input.nextDouble();
System.out.println ("Enter the number of months");
int months = input.nextInt();
double worth = amount + amount * percentage / 1200;
for (int i = 1; i < months; i++) {
amount = worth;
worth = amount + amount * percentage / 1200;
}
System.out.print(worth);
}
}
Thanks! Solved it by using
{
System.out.print("Month " + i + " = " + worth);
amount = worth;
worth = amount + amount * percentage / 1200;
instead of while loop.
It works now :) Thanks so much!
I have the program working I just need help cutting off the extra numbers, Im not very skilled at using the printf statements when printing in Java. When I run it I get output like 1225.043 Here is what I have:
import java.util.Scanner;
public class Comparison {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
float amount;
double principal = 1000.00;
double rate;
System.out.println("Enter interest rate");
rate = keyboard.nextDouble();
System.out.println("Year" +" "+ "Amount on deposit");
for(int year = 1; year <= 10; ++year)
{
amount = (float) (principal * Math.pow(1.0 + rate, year));
System.out.println(year+ " "+ amount);
System.out.println();
}
}
}
Try
System.out.printf("%2d %.2f%n", year, amount);
Output:
Enter interest rate
0.1
Year Amount on deposit
1 1100.00
2 1210.00
3 1331.00
4 1464.10
5 1610.51
6 1771.56
7 1948.72
8 2143.59
9 2357.95
10 2593.74