首页 > 解决方案 > 为什么在 for 循环后不打印计数?

问题描述

每次循环后都会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--;
}

标签: javaarraysfor-loopjava.util.scannerarrayindexoutofboundsexception

解决方案


以下代码块中的条件将导致ArrayIndexOutOfBoundsExceptioni = n - 1时,if ((a[i + 1] - a[i]) > 2)将尝试从a[n - 1 + 1]ie获取一个a[n]您已经知道无效的元素,因为 in 的索引在toa[]的范围0n - 1

for (int i = 0; i < n; i++) {
    if ((a[i + 1] - a[i]) > 2)

你可以这样说

for (int i = 0; i < n -1 ; i++) {
    if ((a[i + 1] - a[i]) > 2)

在此更正之后,下面给出的是示例运行的结果:

1
5
1 2 5 6 7
2 3

这是因为count1++被执行为1 2,5 66 7whilecount++仅被执行为2 5


推荐阅读