【问题标题】:i got Runtime Error for my code ,can anyone help me to find out where i am wrong我的代码出现运行时错误,谁能帮我找出我错在哪里
【发布时间】:2017-07-21 08:24:38
【问题描述】:

下面给出的代码出现运行时错误 - NZEC。我无法理解为什么。谁能帮我解决这个问题。

问题说明: 一个城市中存在各种信号塔。信号塔排列在一条水平直线上(从左到右),每个信号塔从右到左方向传输一个信号。塔如果 A 塔位于 B 塔左侧且 A 塔高于 B 塔,则 A 应阻挡 B 塔的信号。因此,给定塔的信号范围可以定义为:

{(指定塔左侧高度小于或等于指定塔高度的连续塔的数量)+ 1}。

你需要找到每个塔的范围。

输入

第一行包含一个整数 T,指定测试用例的数量。

第二行包含一个整数 n,指定塔的数量。

第三行包含 n 个空格分隔的整数 (H[i]),表示每个塔的高度。

输出

打印每个塔的范围(用空格分隔)。

约束

1

2

1

我的代码

import java.util.*;
import java.io.*;



class TestClass {
    public static void main(String args[] ) throws Exception {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
        Scanner sc = new Scanner(System.in);
       while(t!=0)
       {
           int n=Integer.parseInt(br.readLine());

           int arr[]=new int[n-1];
           int atest[]=new int[n-1];

           for (int i=0;i<n;i++)
           {
               arr[i]=sc.nextInt();
           }

           for(int j=n-1;j>=0;j--)
           {
               int count=0;
              int temp=j-1;
               while(arr[j]>=arr[temp])
               {

                   count++;
                   temp--;  

               }
               atest[j]=count;
           }

           for(int k=0;k<n;k++)
           {
              System.out.println(atest[k]+1);  
           }

           t--;

       }



    }
}

【问题讨论】:

  • 两个问题:1. 您可能在 while 循环中创建了太多数组 2. 您正在使用 Scanner 以及 BufferedReader 这可能会导致问题。

标签: java error-handling stack runtime infinite-loop


【解决方案1】:
       int arr[]=new int[n-1];
       int atest[]=new int[n-1];

       for (int i=0;i<n;i++)
       {
           arr[i]=sc.nextInt();
       }

因为数组长度为n-1(arr.length = n-1)

这就是您收到 ArrayIndexOutOfBoundsException 的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 2021-07-28
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多