提交Kattis的heliocentric题目时出现运行时错误求排查
Kattis平台heliocentric题目Runtime Error排查求助
提交Kattis平台的heliocentric题目代码时,一直出现Runtime Error。修改过部分代码,也咨询过朋友,但始终找不到问题所在。以下是我的Java代码、测试输入和预期输出,求帮忙排查问题。
我的代码
import java.util.Scanner; public class heliocentric { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int inE; int inM; boolean collin; int days; for (int i = 1; i < 10; i++) { days = 0; collin = false; inE = scan.nextInt(); inM = scan.nextInt(); if (inE < 0 || inM < 0) { collin = true; } while (collin != true) { if (inE == 0 && inM == 0) { break; } inE++; if (inE == 365) { inE = 0; } inM++; if (inM == 687) { inM = 0; } days++; if (inE == 0 && inM == 0) { collin = true; } } System.out.println("Case " + i + ": " + days); } scan.close(); } }
测试输入
0 0 364 686 360 682 0 1 1 0
预期输出
Case 1: 0 Case 2: 1 Case 3: 5 Case 4: 239075 Case 5: 11679
问题排查与修复
Runtime Error的核心原因是固定循环次数读取输入:代码中用for (int i = 1; i < 10; i++)强制循环9次,但测试输入只有5组数据。当读完第5组后,scan.nextInt()会试图读取不存在的输入,抛出NoSuchElementException,导致运行时错误。
另外,代码中存在逻辑冗余:判断inE < 0 || inM < 0设置collin = true,但题目输入应为非负整数,这部分判断可移除。
修改后的代码如下:
import java.util.Scanner; public class heliocentric { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int caseNum = 1; while (scan.hasNextInt()) { int inE = scan.nextInt(); int inM = scan.nextInt(); int days = 0; while (!(inE == 0 && inM == 0)) { inE = (inE + 1) % 365; inM = (inM + 1) % 687; days++; } System.out.println("Case " + caseNum + ": " + days); caseNum++; } scan.close(); } }
修改点说明:
- 用
while(scan.hasNextInt())替代固定次数循环,确保读取所有输入直到结束。 - 用取模运算简化日期循环逻辑,替代原有的条件判断,代码更简洁。
- 移除冗余的负数判断逻辑,符合题目输入规范。
- 调整变量定义位置,让代码结构更清晰。
内容的提问来源于stack exchange,提问作者Darklys Lord
相关产品推荐
相关产品推荐

