0

I need help with regards to where to put a while loop on this code. I just began studying Java a few weeks ago. I would like to write in a sentinel value of -1, if entered, the program shall exit. As long as user input is not -1, keep asking repeating the program.

When I put the while loop, "while(currentPop != -1)", below the first question, "Enter current population", the program runs its first course successfully. However, it does not loop back to the first question. Instead, it goes directly to the second question, "Enter birth rate:".

How shall I proceed and make sure that the first question keeps getting asked after running through the loops?

Thank you all!

import java.util.Scanner;

public class Population
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        double birthRate, deathRate;
        double currentPop = 0; 
        double newPop;
        long years;

        System.out.print("Enter current population or -1 to exit: ");
        currentPop = scan.nextDouble();

        System.out.print("Enter birth rate: ");
        birthRate = scan.nextDouble();

        System.out.print("Enter death rate: ");
        deathRate = scan.nextDouble();
        newPop = 0;
        years = 0;          

        System.out.println("===================");
        System.out.println("YEAR     POPULATION");
        System.out.println("===================");

        if (birthRate > deathRate) {
            System.out.printf("0   %,15d\n", (int)currentPop);
            double growthRate = (birthRate - deathRate);
            double doublingTime = Math.log(2) / 
                                Math.log(1 +(growthRate/100)); 
            for (years = 1; years <= (doublingTime+1); years++) {
                newPop = ((growthRate/100) * currentPop) + currentPop;
                currentPop = newPop;
                System.out.printf("%,d   %,15d\n",years,(int)currentPop);
            }
            System.out.printf("\nIt will take %,d years to reach double " 
                            + "the population of %,d\n\n",
                              (int)(doublingTime + 1),(int)currentPop);   
        } else if (birthRate < deathRate) {
            System.out.printf("0   %,15d\n", (int)currentPop);
            double growthRate = (birthRate - deathRate);
            double decreaseTime = Math.log(1/currentPop) 
                                  / Math.log(1 + (growthRate/100));
            for (years = 1; years < (1 + decreaseTime) ; years++) {
                newPop = ((growthRate/100) * currentPop) + currentPop;
                currentPop = newPop;
                System.out.printf("%,d   %,15d\n",years,(int)currentPop);
            }
            System.out.printf("\nPopulation will be zero in %,d years.\n",
                             (int)decreaseTime + 1);
        } else if(birthRate == deathRate) {
        System.out.printf("0   %,15d\n", (int)currentPop);
        double growthRate = (birthRate - deathRate);
        double decreaseTime = Math.log(1/currentPop) 
                              / Math.log(1 + (growthRate/100));
        for (years = 1; years < (1 + decreaseTime) ; years++) {
            newPop = ((growthRate/100) * currentPop) + currentPop;
            currentPop = newPop;
            System.out.printf("%,d   %,15d\n",years,(int)currentPop);
        }
        System.out.printf("\nPopulation is stable.");
    }
}

}

7
  • 3
    Possible duplicate of Using while loop in java Commented Jul 2, 2018 at 6:31
  • You need to put the question and scanning in a loop and move the handling of the answers into a separate method that is called from inside the loop. Commented Jul 2, 2018 at 6:32
  • 2
    Where is the while-loop in your code? I can't seem to find it. Commented Jul 2, 2018 at 6:32
  • Have you used debugger? Why not? Commented Jul 2, 2018 at 6:32
  • 1
    Try learning by making smaller examples. For starters, ask question with a minimal reproducible example Commented Jul 2, 2018 at 6:34

5 Answers 5

3

Exit the program

Simply return from the main method

System.out.print("Enter current population or -1 to exit: ");
currentPop = scan.nextDouble();

if (currentPop == -1.0) {
    return;
}

System.out.print("Enter birth rate: ");

Loop the program with an exit or restart

Use break or continue within the body of a looping construct

while (true) {
    System.out.print("Enter current population or -1 to exit: ");
    currentPop = scan.nextDouble();

    if (currentPop == -1) {
        break;
    } else if (currentPop <= 0) {
        System.out.println("Population must be positive");
        continue; // restart the loop
    }

    System.out.print("Enter birth rate: ");

    ...
}
System.out.println("Done!");

A function that will not accept -1

You can abstract out a repeated task (multiple inputs) using a method

public static double getValue(Scanner s, String msg) {
  double value = -1;
  while (value == -1) {
    System.out.print(msg);
    value = s.nextDouble();
  }
  return value;
}

In the main method

currentPop = getValue(scan, "Enter current population: ");
birthRate = getValue(scan, "Enter birth rate: ");
Sign up to request clarification or add additional context in comments.

Comments

0

While loops will repeat only the code they contain. So this code:

System.out.print("Enter current population or -1 to exit: ");
currentPop = scan.nextDouble();

while (currentPop != -1) {
    System.out.print("Enter birth rate: ");
    birthRate = scan.nextDouble();

    // the rest of your code
}

will only repeat what's inside the while loop. In this case, it will only ask for the birth rate.

The actual code you want is:

while (true) {
    System.out.print("Enter current population or -1 to exit: ");
    currentPop = scan.nextDouble();

    if (currentPop == -1) {
        break;
    }

    System.out.print("Enter birth rate: ");
    birthRate = scan.nextDouble();

    // the rest of your code
}

Let's break this down.

If you want the current population to be asked for again, you need to put that line within the while loop.

I don't know if you're familiar with break, but you said you were new to this. What break does is exits whatever loop it's in. This, along with the while (true) means the while loop will run forever, unless the if statement is called. Hope that helps!

2 Comments

ah. that clears it up for me! Thank you so much! I was trying too hard in not writing an if statement inside the while block.
Glad I could help!
0

I think you should add while(currentPop != -1) { before first question and rest of code. After that line remember to set currentPop = 0 and on the end of code }. edit: And of course after the first question if (currentPop == -1) break;

Comments

0

Here is the code that you want -

import java.util.Scanner;

public class Population
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        double birthRate, deathRate;
        double currentPop = 0; 
        double newPop;
        long years;

        while(true) {
            System.out.print("Enter current population or -1 to exit: ");
            currentPop = scan.nextDouble();
            if(currentPop == -1)
                break;

            System.out.print("Enter birth rate: ");
            birthRate = scan.nextDouble();

            System.out.print("Enter death rate: ");
            deathRate = scan.nextDouble();
            newPop = 0;
            years = 0;          

            System.out.println("===================");
            System.out.println("YEAR     POPULATION");
            System.out.println("===================");

            if (birthRate > deathRate) {
                System.out.printf("0   %,15d\n", (int)currentPop);
                double growthRate = (birthRate - deathRate);
                double doublingTime = Math.log(2) / 
                                    Math.log(1 +(growthRate/100)); 
                for (years = 1; years <= (doublingTime+1); years++) {
                    newPop = ((growthRate/100) * currentPop) + currentPop;
                    currentPop = newPop;
                    System.out.printf("%,d   %,15d\n",years,(int)currentPop);
                }
                System.out.printf("\nIt will take %,d years to reach double " 
                                + "the population of %,d\n\n",
                                  (int)(doublingTime + 1),(int)currentPop);   
            } else if (birthRate < deathRate) {
                System.out.printf("0   %,15d\n", (int)currentPop);
                double growthRate = (birthRate - deathRate);
                double decreaseTime = Math.log(1/currentPop) 
                                      / Math.log(1 + (growthRate/100));
                for (years = 1; years < (1 + decreaseTime) ; years++) {
                    newPop = ((growthRate/100) * currentPop) + currentPop;
                    currentPop = newPop;
                    System.out.printf("%,d   %,15d\n",years,(int)currentPop);
                }
                System.out.printf("\nPopulation will be zero in %,d years.\n",
                                 (int)decreaseTime + 1);
            } else if(birthRate == deathRate) {
                System.out.printf("0   %,15d\n", (int)currentPop);
                double growthRate = (birthRate - deathRate);
                double decreaseTime = Math.log(1/currentPop) 
                                      / Math.log(1 + (growthRate/100));
                for (years = 1; years < (1 + decreaseTime) ; years++) {
                    newPop = ((growthRate/100) * currentPop) + currentPop;
                    currentPop = newPop;
                    System.out.printf("%,d   %,15d\n",years,(int)currentPop);
                }
                System.out.printf("\nPopulation is stable.");
            }
        }
        scan.close();
    }
}

Comments

-1

To implement a while, loop at first you've to determine the termination condition, and it works till the condition reaches the termination condition (i.e.false),its syntax could be as

while(true) { //your code} 

1 Comment

Question is asked for java. Why give C++ example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.