Java 此程序的NZEC错误原因?

Java 此程序的NZEC错误原因?,java,algorithm,sorting,arraylist,runtime-error,Java,Algorithm,Sorting,Arraylist,Runtime Error,我有一个问题,我需要找到用户输入的第二个最大元素。这是一个在线实践问题,我不明白为什么服务器在我提交代码时会回复NZEC错误。有人能告诉我代码的哪一部分容易出现这种错误,以及如何处理这种错误吗 Sample Input:= Sample Output:= 2 7 1 3 5 7 8 -1 16 12 23 16 0 2 -1 p.S-第一个输入是测试用例的数量。第二和第三输

我有一个问题,我需要找到用户输入的第二个最大元素。这是一个在线实践问题,我不明白为什么服务器在我提交代码时会回复NZEC错误。有人能告诉我代码的哪一部分容易出现这种错误,以及如何处理这种错误吗

Sample Input:=                Sample Output:=

2                             7
1 3 5 7 8 -1                  16
12 23 16 0 2 -1
p.S-第一个输入是测试用例的数量。第二和第三输入分别为实际用户输入。用户输入总是以-1终止

这是我的密码:=

class SecondLargest {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int testcase=Integer.parseInt(sc.nextLine());

        while(testcase-->0){
            ArrayList<Long> al=new ArrayList<>();
            long num=0;
            long i=0;
            while((num=(sc.nextLong()))!=-1){
                al.add(num);
                i++;
            }
            Collections.sort(al);
            if(al.size()==0){
                System.err.println("");
            }
            else if(al.size()==1){
                System.out.println(al.get(0));
            }
            else if(al.size()>1){
            System.out.println(al.get((int)(al.size()-2)));
            }
        }
        }
    }
第二类{
公共静态void main(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
int testcase=Integer.parseInt(sc.nextLine());
而(测试用例-->0){
ArrayList al=新的ArrayList();
long num=0;
长i=0;
而((num=(sc.nextLong())!=-1){
al.add(num);
i++;
}
集合。排序(al);
如果(al.size()==0){
System.err.println(“”);
}
else if(al.size()==1){
System.out.println(al.get(0));
}
否则,如果(总尺寸()>1){
System.out.println(al.get((int)(al.size()-2));
}
}
}
}

PSS-大型输入集将用于测试程序

如果只传递一个/零元素,则将在第行获得索引越界异常:

System.out.println(al.get((int)(i-2)));//negative scenario where you might be expected to return -1?
找不到第二个最大元素,但找到唯一的元素,即最大元素

将if/elseif块更改为

    if(al.size()<2){
        System.err.println("");
    } else {
        System.out.println(al.get((int)(al.size()-2)));
    }

if(总尺寸()可能重复:注释是绝对无效的。我已经看到了你的链接,它与上述问题无关。我已经为1/0元素添加了两个S.o.p,与上面提到的一个元素一起。但它仍然给我一个NZEC。更新你的代码。你为什么要使用long?你在寻找什么范围?没有输入约束但如果其中一个元素大于int,则无法判断这些值是否总是在整数的范围内。
    if(al.size()<2){
        System.err.println("");
    } else {
        System.out.println(al.get((int)(al.size()-2)));
    }