java - 数组链接错误 java.lang.ArrayIndexOutOfBoundsException: 4
问题描述
我正在尝试制作一个程序,询问用户 4 个月的数据使用情况。然后确定他们是否超过了限制,如果超过了,额外的成本就会起作用。
但是当我尝试计算这个时我得到了一个错误。错误是:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Simonly.main(Simonly.java:33)
这反过来
if (verbruik[i] > MB) {
我该如何解决这个问题?欢迎任何建议!
我的完整代码:
import java.util.Scanner;
public class Simonly {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Dit programma is gemaakt door Zakaria El-Bouchahati, IC201, 500785448\n");
double PRIJS_PRIJS = 9.95;
double MEEPRIJS = 0.025;
int MB = 3000;
double prijs = 0.0;
double totaalPrijs = 0.0;
String[] MAANDEN ={"juli", "augustus", "september", "oktober"};
int[] verbruik = new int[MAANDEN.length];
System.out.println("Geef je verbruik in MB per maand");
int i;
for(i = 0; i < MAANDEN.length; ++i) {
do {
System.out.print("\t" + MAANDEN[i] + ": ");
verbruik[i] = input.nextInt();
if (verbruik[i] < 0) {
System.out.println("Verkeerde input hoger dan nul!");
}
} while(verbruik[i] <= 0);
}
System.out.println("MAAND \t \t MB KOSTEN");
for(i = 0; i <= verbruik.length; ++i) {
if (verbruik[i] > MB) {
prijs -= MB;
totaalPrijs += prijs * MEEPRIJS;
} else {
totaalPrijs += MEEPRIJS;
}
}
for(i = 0; i <= verbruik.length; ++i) {
System.out.printf("-%20s " + MAANDEN[i]);
System.out.println(MAANDEN[i] + "\t" + verbruik + "\t" + prijs);
}
}
}
解决方案
MAANDEN.length is 4, verbruik length is 4, the loop will go from 0 to 4, that is: 0, 1, 2, 3, 4 which if you count them are 5 numbers. And the exception is telling you that 4 is an out of bounds value. To avoid this sort of problems and not to have to think about indexes, use the "enhanced form of for loop":
for (int verbruikValue : verbruik) {
if (verbruikValue > MB) ...
}
推荐阅读
- python - scipy.fft.fft 输出行为与 T/f_signal 比率
- c# - WPF:打开新窗口并关闭当前整个应用程序时冻结
- c++ - 如何修复这种不推荐使用的 std::allocator ?
- c++ - C++ 类中的内存处理
- javascript - 检索最终属性的问号语法
- spring - 登录成功后页面仍然显示 403 在 spring security 中被禁止
- file - 如何从 grep 搜索中获取输出中文件的日期?
- oracle - 对 Oracle forms 12c formsweb.cfg pageTitle 参数的更改不起作用 - pageTitle 保持不变
- mysql - 用 Woocommerce 产品的长描述交换简短描述
- networking - Istio 网关:api.example.com 不起作用。blaapi.example.com 确实有效。为什么?