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

Java查找满足a<b<c及a+b+c=1000的9位整数代码异常退出求助

问题排查结果

核心错误1:平方值计算时机错误

你在给a、b、c赋值前就计算了平方值a2、b2、c2,此时a、b、c都是初始值0,三个平方值永远等于0,a2 < b2 && b2 < c2的条件永远不成立。

核心错误2:首次循环不满足就直接退出程序

else分支直接调用System.exit(0),只要第一次循环(abc=220000000)不满足条件,程序就直接终止,根本不会遍历后续的数值。

优化提示

因为a的取值范围固定是220~239(abc前三位),结合a+b+c=1000且a<b<c的条件,其实可以提前推导出b、c的取值范围,减少不必要的循环遍历,但上面两个问题是直接导致无输出的核心原因。


修正后的代码

class Main {
  public static void main(String[] args) {
    int abc;
    int total = 1000;
    for (abc = 220000000; abc < 240000000; abc++) {
      String string1 = Integer.toString(abc);
      // 先拆分赋值a、b、c
      int a = Integer.parseInt(string1.substring(0, 3));
      int b = Integer.parseInt(string1.substring(3, 6));
      int c = Integer.parseInt(string1.substring(6, 9));
      // 赋值完成后再计算平方值
      int a2 = squared(a);
      int b2 = squared(b);
      int c2 = squared(c);
      if (a < b && a < c && b < c && a2 < b2 && b2 < c2 && a + b + c == total) {
        System.out.println("The answer is " + abc);
        // 找到匹配结果后再退出,也可注释该行查找所有符合条件的数值
        System.exit(0);
      }
      // 不满足条件就进入下一次循环,不要直接终止程序
    }
  }

  public static int squared(int x) {
    return (x * x);
  }
}

内容的提问来源于stack exchange,提问作者Maxim Sergeyev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:06:04