gpt4 book ai didi

java - 亚马逊 Mosquitos - ArrayIndexOutOfBounds

转载 作者:行者123 更新时间:2023-12-02 05:07:59 25 4
gpt4 key购买 nike

我正在尝试制作一个小Java程序。

该程序有 3 个整数的输入:S:开始的蚊子,K:每只蚊子生下的 child 的数量,N:我们“调查”的天数。

亚马逊地区的每只蚊子只能存活 1 天。第 0 天,我们从 S 蚊子开始。每只蚊子活着的一天,只做两件事。首先,它攻击一个人。攻击后,蚊子立即产下K只蚊子,然后死亡。

程序的输出必须是N天内将受到攻击的人类数量。

例如,对于输入 (1,2,12),输出必须为 8191 (1+2+4+8+...+4096)。

我的尝试如下:

public class AmazMosq {

public static int reproduction(int starting, int children, int days) {

int[] mosquitos = new int[days];
mosquitos[0] = starting;

int bites = starting;

for (int i = 1; i <= days; i++) {
mosquitos[i] = mosquitos[i-1] * children;

bites += mosquitos[i];
}

return bites;

}


public static void main(String[] args) {

System.out.println("Enter the number of starting mosquitos:");
int starting = IOUtil.readInt();

System.out.println("Enter the number of children each mosquito makes everyday:");
int children = IOUtil.readInt();

System.out.println("Enter the number of days:");
int days = IOUtil.readInt();

System.out.println(reproduction(starting, children, days));

}

}

其中 IOUtil.readInt() 是读取输入 Int 的函数。

但是,我收到此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
at AmazMosq.reproduction(AmazMosq.java:11)
at AmazMosq.main(AmazMosq.java:34)

这是什么意思以及我做错了什么?谢谢!

最佳答案

这里:

for (int i = 1; i <= days; i++) {

您可以像这样初始化数组:

int[] mosquitos = new int[days];

因此您可以访问 0 到 days - 1 之间的元素。您正在 for 循环内访问元素 mosquitos[days],这是问题的原因,特别是在这里:

mosquitos[i] = mosquitos[i-1] * children;
//^ here ^
bites += mosquitos[i];
// ^ here ^

更改为

for (int i = 1; i < days; i++) {

或者更好的是:

for (int i = 1; i < mosquitos.length; i++) {

关于java - 亚马逊 Mosquitos - ArrayIndexOutOfBounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27607188/

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