为什么 for 循环后不打印计数?[已结束]

Why the count is not printing after for loop? [closed]

提问人:Mayur Hovale 提问时间:11/15/2020 最后编辑:Arvind Kumar AvinashMayur Hovale 更新时间:1/18/2021 访问量:239

问:


这个问题是由一个错别字或一个无法再重现的问题引起的。虽然类似的问题可能在这里成为主题,但这个问题的解决方式不太可能帮助未来的读者。

3年前关闭。

在每个循环之后并更新。在输入后,我没有得到任何输出。countcount1Scanner

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--;
}
Java 数组 for 循环 java.util.scanner arrayindexoutofboundsexception

评论

1赞 Eran 11/15/2020
您只为 t 赋值一次。如果该值不为 0,则循环永无止境。
0赞 Mayur Hovale 11/15/2020
即使添加 t--;它显示了同样的事情
0赞 Kevin Anderson 11/15/2020
你确定你的程序没有死吗?因为包含它的循环一直运行到 ,语句(特别是位)将在达到 的值时爆炸,并且程序永远不会到达循环后面的值。ArrayIndexOutOfBoundsExceptionfori == n-1if ((a[i + 1] - a[i]) > 2)a[i+1]in-1System.out.println

答:

0赞 Zahid Khan 11/15/2020 #1
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+1a[i + 1]ArrayIndexOutOfBoundsException.

0赞 Razib 11/15/2020 #2

由于您尝试连续进行测试用例输入,因此仅在此处不起作用。我将在这里发布一个通用结构。请尝试以下方法 -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();
    }
0赞 Arvind Kumar Avinash 11/15/2020 #3

以下代码块中的条件将导致 as when i = n - 1,将尝试从 i.e 中获取一个元素,因为 中的索引在 to 的范围内:ArrayIndexOutOfBoundsExceptionif ((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

这是因为 被执行为 ,而 while 只被执行 。count1++1 2,5 66 7count++2 5