gpt4 book ai didi

java - 代码似乎跳过了 if 或 for 循环

转载 作者:行者123 更新时间:2023-12-01 15:32:54 25 4
gpt4 key购买 nike

  1. 当我输入满足所有要求且不会触发任何错误的输入时,程序会在最后一次输入后退出,就像跳过 forif 循环。

  2. 此外,在 System.out.printf("输入您的第二个物种的名称:"); 之后,它不会允许任何输入,它只是跳到下一个提示。我不知道为什么会这样。上面询问第一个物种信息的部分工作正常。

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");
}
}
}
}
}
<小时/>

这用于predictPopulation():

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;
}

最佳答案

  1. 这是因为在物种 2 超过物种 1 后,您永远不会打印任何内容,除非在非常特殊的情况下,物种 2 和物种 1 在某一年的人口完全相同

  2. 这是因为,当您输入物种 1 的增长率时,您输入一个整数,然后按 Enterkeyboard.nextInt() 吞下整数,但将换行符保留在输入缓冲区上,因此后续的 keyboard.nextLine() 认为有一个空行在等待它.

关于java - 代码似乎跳过了 if 或 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9354952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com