【问题标题】:Why the count is not printing after for loop? [closed]为什么在 for 循环后不打印计数? [关闭]
【发布时间】:2021-02-26 17:04:27
【问题描述】:

在每个循环 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--;
}

【问题讨论】:

  • 您只为 t 赋值一次。如果该值不为 0,则循环永远不会结束。
  • 即使在添加了 t--;它显示了同样的东西
  • 您确定您的程序没有因ArrayIndexOutOfBoundsException 而死吗?因为包含它的for 循环一直运行到i == n-1,所以当i 确实达到n-1 的值时,语句if ((a[i + 1] - a[i]) &gt; 2)(特别是a[i+1] 位)将立即爆炸,并且程序永远不会到达循环之后的System.out.println

标签: java arrays for-loop java.util.scanner arrayindexoutofboundsexception


【解决方案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++) {

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

【讨论】:

    【解决方案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();
        }
    

    【讨论】:

      【解决方案3】:

      以下代码块中的条件将导致 ArrayIndexOutOfBoundsExceptioni = n - 1 时,if ((a[i + 1] - a[i]) &gt; 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 执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-07
        • 1970-01-01
        • 1970-01-01
        • 2021-10-10
        • 2015-02-15
        • 1970-01-01
        • 2019-12-23
        相关资源
        最近更新 更多