Kent Edward Sorenson
Kent Edward Sorenson

Reputation: 41

Working on While loops

I was given a problem in my new programming class, and I've only ever used Python. Here is my problem:

Write a program that prints the balance of an account after the first, second, and third year. The account has an initial balance of $1,000 and earns 5 percent interest per year.

I understand that my math may be flawed but the important thing is using the correct format and just getting my program to run. Here is my code:

public class P14MIS207 {
    public static void main(String[] args) 
    {
        int year_one_balance, month, x;
        year_one_balance = 1000;
        interest = (.05/12) * (year_one_balance);
        month = 0;
        x = 36;
        while(month <= x);
            month++;
            year_one_balance += interest;
            System.out.println(year_one_balance);
            // TODO code application logic here
    }
}

Upvotes: 0

Views: 2234

Answers (2)

Aritro Sen
Aritro Sen

Reputation: 357

You can do something like this. -

double principal=1000;
    int rate=5;
    double interest=0;
    int year=1;
    while(year<=3){
        interest=(principal*rate*year)/100;
        principal=principal+interest;
        System.out.println("Amount after "+year+" year is: $"+principal);
        year++;
    }

Upvotes: 0

Donald
Donald

Reputation: 1200

You don't need the semicolon after the while keyword, and you want to wrap the interior of the loop in curly braces (as opposed to how you use spaces in Python). Try:

while( month <= x){
    month++;
    year_one_balance += interest;
    System.out.println(year_one_balance);
    // TODO code application logic here
}

Upvotes: 3

Related Questions