当我在这段代码的底部运行 for
循环时,我得到一个无限循环,每次使用 i 都会输出
每次都会增加并且不会停止。我很确定这是一个小问题,我只是无法指出......if
语句中的输出
import java.util.Scanner;
public class HW2johnson_pp1 {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Please enter the species with the higher" +
" population first\n");
System.out.printf("Enter the name of your first species ");
String Species1 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop1 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth1 = keyboard.nextInt();
System.out.printf("Enter the name of your second species: ");
String Species2 = keyboard.nextLine();
System.out.printf("Enter the species' population: ");
int Pop2 = keyboard.nextInt();
System.out.printf("Enter the species' growth rate: ");
int Growth2 = keyboard.nextInt();
if (Pop2 > Pop1) {
System.out.printf("The first population must be higher. \n");
System.exit(0);
}
Species input1 = new Species();
input1.name = Species1;
input1.population = Pop1;
input1.growthRate = Growth1;
Species input2 = new Species();
input2.name = Species2;
input2.population = Pop2;
input2.growthRate = Growth2;
if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <=
(input1.predictPopulation(2) - input2.predictPopulation(2))){
System.out.printf(Species2 + " will never out-populate " +
Species1 + "\n");
}
else {
for (int i = 0; input2.predictPopulation(i) <=
input1.predictPopulation(i); i++) {
if (input2.predictPopulation(i) == input1.predictPopulation(i)) {
System.out.printf(" will out-populate \n");
}
}
}
}
}
<小时/>
public int predictPopulation(int years)
{
int result = 0;
double populationAmount = population;
int count = years;
while ((count > 0) && (populationAmount > 0))
{
populationAmount = (populationAmount +
(growthRate / 100) * populationAmount);
count--;
}
if (populationAmount > 0)
result = (int)populationAmount;
return result;
}
最佳答案
这个:
if (Pop2 > Pop1) {
Species2 = Species1;
Pop2 = Pop1;
Growth1 = Growth2;
}
没有意义。显然,您的目的是“交换”两个群体的值,但相反,您只是使两个群体相同,因此对于 years
的任何值, predictPopulation(years)
两个对象都是相同的。
编辑添加:此测试:
if ((input1.predictPopulation(1) - input2.predictPopulation(1)) <
(input1.predictPopulation(2) - input2.predictPopulation(2)))
不是判断物种 2 最终是否会超越物种 1 的有效方法。如果物种 2 具有更大的比例增长率 ( growthRate
),那么它最终将超越物种 1,甚至如果在最初几年,它的绝对增长率较低。 (这仅与您的无限循环无关 - Dampsquid 指出,如果您使用 <=
而不是 <
,您将不会有无限循环 - 但这是您需要解决的问题。)
关于java - Java中的无限循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354375/