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

提交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();
  }
}

修改点说明:

  1. 用while(scan.hasNextInt())替代固定次数循环,确保读取所有输入直到结束。
  2. 用取模运算简化日期循环逻辑,替代原有的条件判断,代码更简洁。
  3. 移除冗余的负数判断逻辑,符合题目输入规范。
  4. 调整变量定义位置,让代码结构更清晰。

内容的提问来源于stack exchange,提问作者Darklys Lord

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:55:31