Colby Bradbury
Colby Bradbury

Reputation: 77

New Java Programmer, whats wrong with this program?

It gets to the point where it has to print the line System.out.printf("%4s%22s%24s\n","Year"...), and then just stops without printing.

public class WorldPopulationGrowth {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner input = new Scanner( System.in);
        long BasePopulation; //The base, or current population
        double GrowthRate; //The rate of increase
        double GrowthResult; // The pop after growth rate increase

        //Time to obtain the numbers needed for Calculation
        //Specifically, the growth rate and the base population
        System.out.println("Welcome to the world population calculator");
        System.out.print("Enter the current world population:");
        BasePopulation = input.nextLong();
        System.out.println("Enter the current growth rate: (e.g, 1.14% would be .0114): ");
        GrowthRate = input.nextDouble();
        int Year = 1; //I need this for the next part
        System.out.printf("%4s%22s%24s\n", "Year", "Estimated Population", "Change from prior Year");
        while (Year <= 75); {// Start of the while
            GrowthResult = BasePopulation * (1 + GrowthRate);
            System.out.printf("%4d%22d%24d\n", Year, (long) GrowthResult, (long) GrowthResult - BasePopulation);
            BasePopulation = (long) GrowthResult;
        }//End of the while
    }//End of public static
}//End of class

Upvotes: 0

Views: 1221

Answers (2)

Phil S
Phil S

Reputation: 179

Try removing semicolon from this line

while (Year <= 75); {// Start of the while

Should be:

while (Year <= 75) {// Start of the while

Upvotes: 2

yshavit
yshavit

Reputation: 43391

You've got a semicolon after your while loop. That semicolon is an empty statement, and that's what gets executed in the loop. After that, you have an anonymous block (which is what you want to be executed in the loop). It's equivalent to this:

while (Year <= 75) {
    // empty
}
{
    // anonymous block
    GrowthResult = BasePopulation * (1 + GrowthRate);
    ...

The fix is to remove the semicolon.

Upvotes: 7

Related Questions