Мне нужна помощь в отношении того, где поместить цикл while в этот код. Я только начал изучать Java несколько недель назад. Я хотел бы написать в дозорном значении -1, если введено, программа должна выйти. Пока пользовательский ввод не -1, продолжайте спрашивать повторение программы.
Когда я ставлю цикл while, "while (currentPop! = -1)" , под первым вопросом "Введите текущую популяцию", программа успешно проходит свой первый курс. Тем не менее, он не возвращается к первому вопросу. Вместо этого он сразу переходит ко второму вопросу: «Введите коэффициент рождаемости:».
Как мне поступить и убедиться, что первый вопрос продолжает задаваться после прохождения циклов?
Спасибо всем!
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.");
}
}
}