You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

提交至Codeforces的Java代码出现NoSuchElementException,本地VS Code运行正常求助

提交至Codeforces的Java代码出现NoSuchElementException,本地VS Code运行正常求助

大家好,我碰到个棘手的问题:这段代码在本地VS Code里跑给定的测试用例完全没问题,但提交到Codeforces后就抛出NoSuchElementException,提示在测试用例1就出错了,有没有大佬能帮忙排查下问题出在哪?

我的代码:

import java.util.*;

public class SashaAndArrayColoring {

public static void main(String []args){

Scanner sc=new Scanner(System.in);

int t=sc.nextInt();

while(t!=0){

int n=sc.nextInt();

int arr[]=new int[n];

for(int i=0; i<n; i++){

arr[i]=sc.nextInt();

}

if(n==1){

System.out.println("0");

}else {

Arrays.sort(arr);

int sum=0;

for(int i=0; i<n/2; i++){

sum=sum+(arr[n-(i+1)]-arr[i]);

}

System.out.println(sum);

}

}

}

}

测试用例(本地运行正常):

6

5

1 5 6 3 4

1

5

4

1 6 3 9

6

1 13 9 3 7 2

4

2 2 2 2

5

4 5 2 2 3

问题排查与修复方案:

我仔细捋了一遍代码,发现了核心问题:你的循环条件是while(t!=0),但循环体内部完全没有对t进行递减操作!这就意味着t的值永远不会变成0,循环会无限执行下去。

本地测试时,你手动输入完所有测试用例后可能就停止输入了,程序只会卡住但不会立刻抛出异常;但Codeforces是一次性提供完整的测试用例数据,当所有数据被读取完毕后,sc.nextInt()还在尝试读取下一个整数,自然就会抛出NoSuchElementException——因为已经没有输入可以读取了。

修复方法特别简单,只需要在循环体的末尾加上t--,让每次循环后测试用例的计数减1,直到t变为0时正常退出循环:

import java.util.*;

public class SashaAndArrayColoring {

public static void main(String []args){

Scanner sc=new Scanner(System.in);

int t=sc.nextInt();

while(t!=0){

int n=sc.nextInt();

int arr[]=new int[n];

for(int i=0; i<n; i++){

arr[i]=sc.nextInt();

}

if(n==1){

System.out.println("0");

}else {

Arrays.sort(arr);

int sum=0;

for(int i=0; i<n/2; i++){

sum=sum+(arr[n-(i+1)]-arr[i]);

}

System.out.println(sum);

}

// 新增这一行,减少测试用例计数,让循环能正常退出
t--;

}

}

}

修改后,循环会在处理完t个测试用例后自动终止,不会再尝试读取不存在的输入,应该就能解决Codeforces上的运行时异常问题了。

备注:内容来源于stack exchange,提问作者user18253054

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 10:28:00