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.");
}
}
}