【发布时间】:2021-02-26 17:04:27
【问题描述】:
在每个循环 count 和 count1 更新后。在Scanner 中输入后,我没有得到任何输出。
Scanner sc = new Scanner(System.in);
int t = sc.nextInt(); // t=1
while (t != 0) {
int n = sc.nextInt(); // n=5
int a[] = new int[n]; // a = { 1,2,5,6,7 }
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int count = 0, count1 = 0;
for (int i = 0; i < n; i++) {
if ((a[i + 1] - a[i]) > 2) {
count++;
} else {
count1++;
}
}
// this doesn't get printed
System.out.println(count + 1 + " " + count1);
t--;
}
【问题讨论】:
-
您只为 t 赋值一次。如果该值不为 0,则循环永远不会结束。
-
即使在添加了 t--;它显示了同样的东西
-
您确定您的程序没有因
ArrayIndexOutOfBoundsException而死吗?因为包含它的for循环一直运行到i == n-1,所以当i确实达到n-1的值时,语句if ((a[i + 1] - a[i]) > 2)(特别是a[i+1]位)将立即爆炸,并且程序永远不会到达循环之后的System.out.println。
标签: java arrays for-loop java.util.scanner arrayindexoutofboundsexception