【发布时间】:2018-12-10 07:54:03
【问题描述】:
我需要有关在此代码上放置 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.");
}
}
}
【问题讨论】:
-
您需要将问题和扫描放在一个循环中,并将答案的处理转移到一个从循环内部调用的单独方法中。
-
代码中的while循环在哪里?我好像没找到。
-
你用过调试器吗?为什么不呢?
-
尝试通过制作更小的示例来学习。对于初学者,请通过minimal reproducible example 提问
标签: java loops while-loop java.util.scanner