-3

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

3 回答 3

0

以下代码块中的条件将导致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

于 2020-11-15T08:40:57.353 回答
0
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++) {

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

于 2020-11-15T07:56:04.443 回答
0

当您尝试连续输入测试用例t-- 时,此处将不起作用。我将在这里发布一个通用结构。尝试以下方法 -

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();
    }
于 2020-11-15T08:02:50.577 回答