我正在尝试编写一个程序,该程序需要一个人口的出生率和死亡率并循环年度人口,直到它达到0或两倍。
我的问题是,它不断地循环无数的难以辨认的数字,我无法解决它。
import java.util.Scanner;
public class Hwk6 {
public static void main (String[] args) {
int currentYear, currentPopulation;
double birthRate, deathRate;
Scanner stdin = new Scanner(System.in);
System.out.println("\nPopulation Estimator\n");
System.out.println("Enter Year");
currentYear = stdin.nextInt();
System.out.println("Enter Current Population");
currentPopulation = stdin.nextInt();
System.out.println("Enter Birthrate of Population");
birthRate = stdin.nextDouble();
System.out.println("Enter Deathrate of Population");
deathRate = stdin.nextDouble();
int counter = currentPopulation;
System.out.println("Population: ");
while (currentPopulation != -1)
while (counter < currentPopulation * 2) {
System.out.print(counter + " ");
counter = counter + (int)(counter * birthRate - counter * deathRate);
}
System.exit(0);
}
}
答案 0 :(得分:4)
在currentPopulation
循环中的某处更新while
的值,否则while (currentPopulation != -1)
将始终评估为true(除非-1
是原始值价值),你将最终陷入无限循环。
或许你的意思是
if (currentPopulation != -1)
而不是
while (currentPopulation != -1)
答案 1 :(得分:2)
while (currentPopulation != -1)
你的状态永远是真的,因此它将无限迭代。因为您没有在任何地方更改while循环内的currentPopulation
值。
在内部while循环结束后,您需要在外部while循环中的某处更改currentPopulation
的值。
while (currentPopulation != -1) {
while (counter < currentPopulation * 2) {
System.out.print(counter + " ");
counter = counter + (int)(counter * birthRate - counter * deathRate);
}
// Change your `currentPopulation` here
}