# Thread: Homework help: looping problems

1. Registered User
Join Date
Feb 2012
Posts
7

## Homework help: looping problems

Hi,

My homework this week is to create a program that shows the return on an investment. It must ask the user to input the amount of the investment, the number of years, and the interest rate. (if a zero is entered, an error message must instruct the user that was an invalid input) I need the program to then print out the amount of the investment year by year, ie, my output should look like this. I've put in random numbers as an example:

Enter investment amount: 100

Enter number of years: 3

Enter interest rate (as a decimal): .05

Your investment at 5.0 percent is:

After year 1 \$105.00
After year 2 \$110.25
After year 3 \$115.76

And so on, depending on the number of years the user entered at the prompt. I'm having trouble with a) getting the output to print by year instead of as one lump sum, and b) how to define a number in the loop that I don't know yet. I want to use "final int MAX" for that, but I'm not sure how.

I'm also having a problem getting the "not enough information message" to display without the investment output statement printing out afterward. Should I use an else statement for the output? I keep getting problems when I try to do that.

Can anyone help me out with some advice? My code is below.

import java.text.*;
import java.util.*;
public class Investment {

public static void main(String[] args)
{
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);

double investment;
double growth;
double rate;
int years;

Scanner input = new Scanner(System.in);

System.out.print("Enter investment amount: ");
investment = input.nextDouble();

System.out.print("Enter number of years: ");
years = input.nextInt();

System.out.print("Enter interest rate (as a decimal): ");
rate = input.nextDouble();

if (investment <= 0||years <=0 ||rate<=0)
{
System.out.println("Not enough information - amount must be non-zero.");
}

growth = investment * rate * years;

System.out.println("Your investment at " + rate + " is " + df.format(growth));

}
}

2. Registered User
Join Date
Feb 2012
Posts
3

## re: homework

Here's what I came up with... The start of your code stays the same.
Code:
```if (investment <= 0||years <=0 ||rate<=0)
{
System.out.println("Not enough information - amount must be non-zero.");
}

// this loop will provide the individual return per year
for (int i = 1; i <= years; i++){
double profit = investment * rate;   // profit made this year
investment += profit;                // add this profit to the initial investment
System.out.println("Your investment after " + i + " year at " + rate + " is " + df.format(investment));
}```
note that the user input should always be with a ',' and not a '.' else you will get an input error. Maybe you should try and implement a method that checks the user input.

hope this helps.