java - ArrayIndexOutOfBoundsException:索引 3 超出长度 3 的范围
问题描述
我遇到了一个例外,我不明白为什么
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 3;
int[] numbers = new int[n];
float total = 0;
for (int i = 1; i <= 3; i++) {
System.out.println("Please type the number " + i + ":");
numbers[i] = input.nextInt();
total = total + numbers[i];
}
System.out.println("The average of the 3 number is: " + total / n);
}
安慰:
Please type the number 1:
3
Please type the number 2:
4
Please type the number 3:
5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Ejercicio12.main(Ejercicio12.java:17)
解决方案
因为数组索引从 0 开始
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 3;
int[] numbers = new int[n];
float total = 0;
for (int i = 0; i <= 2; i++) {
int row=i+1;
System.out.println("Please type the number " + row + ":");
numbers[i] = input.nextInt();
total = total + numbers[i];
}
System.out.println("The average of the 3 number is: " + total / n);
}
推荐阅读
- javascript - 单击包含一些文本的按钮
- mysql - Laravel:有没有办法执行快速批量更新?
- powershell - 使用 Powershell 将文件上传到 Sharepoint Online (Microsoft 365)(选项 4 - 使用 Microsoft.SharePoint.Client.ClientContext)
- api - Cypress_- 无法加载资源:net::ERR_EMPTY_RESPONSE
- r - 在 R 中,如何将没有相同列的数据框组合到大数据框。谢谢
- ansible - 从 ansible-playbook 获取为 docker-ce 运行的实际命令
- r - 在 R 中找到所有适用的方法
- python - 我如何在相同的场景中使用相同的步骤,但在 pytest-bdd 中使用不同的参数?
- javascript - React Pubnub 聊天。消息复制或根本没有消息
- pandas - 可以使用 np.where 检查向量中的条件,但输出二维数组中的行