为什么在 for 循环后不打印计数?

Why the count is not printing after for loop?

每次循环后 countcount1 都会更新。在 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--;
}
int count=0,count1=0;
for (int i = 0; i < n; i++) 

应替换为

int count=0,count1=0;
for (int i = 0; i < n-1; i++) {

您正在尝试通过 a[i + 1] 访问 n+1 内存位置,即 ArrayIndexOutOfBoundsException.

因为您正在尝试连续获取测试用例输入,所以 t-- 在这里不起作用。我将在这里 post 一个通用的结构。尝试以下方法 -

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for(int i = 0; i < t; i++){
            int n = in.nextInt();
            //do your stuff here
            // now you could take input and process them t times
        }

        //finally don't forget to close the input stream.
        in.close();
    }

以下代码块中的条件将导致 ArrayIndexOutOfBoundsException,因为当 i = n - 1 时,if ((a[i + 1] - a[i]) > 2) 将尝试获取一个元素从 a[n - 1 + 1] 即您已经知道的 a[n] 是无效的,因为 a[] 中的索引在 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 7,而count++只执行了2 5