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

如何修复BigInteger与int不兼容的操作数问题(考拉兹猜想程序)

问题解决:BigInteger与int类型不兼容错误

核心错误原因

你第21行的判断逻辑存在问题:num.remainder(new BigInteger("2")) == 0。BigInteger.remainder()返回的是BigInteger对象,而0是int基本类型,两者不能用==直接比较——==对于对象是比较引用地址而非数值,且类型不匹配也会触发编译报错。

修复方案

把判断偶数的条件改成用equals()比较BigInteger常量,同时推荐使用JDK预定义的BigInteger.TWO、BigInteger.ZERO等常量,避免重复创建对象:

else if (num.remainder(BigInteger.TWO).equals(BigInteger.ZERO))

其他优化点(顺带解决潜在问题)

  • 不要创建多个Scanner实例:你同时用了intIn和strIn两个Scanner,会导致输入读取异常,只用一个Scanner即可。
  • 删除冗余判断:外层while已经判断num.equals(BigInteger.ONE) == false,循环内的if (num.equals(new BigInteger("1")))分支永远不会执行,直接删除即可。
  • 使用BigInteger预定义常量:把new BigInteger("1")、new BigInteger("3")换成BigInteger.ONE、BigInteger.THREE,代码更简洁高效。

修改后的完整代码

import java.math.BigInteger;
import java.util.Objects;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        boolean repeat = true;
        Scanner scanner = new Scanner(System.in); // 仅使用一个Scanner实例

        while (repeat) {
            int i = 0;
            System.out.println("Enter number you want solved, Don't type 0. Use this program with caution");
            BigInteger num = scanner.nextBigInteger();

            while (!num.equals(BigInteger.ONE)) { // 简化判断逻辑
                if (num.remainder(BigInteger.TWO).equals(BigInteger.ZERO)) {
                    num = num.divide(BigInteger.TWO);
                } else {
                    num = num.multiply(BigInteger.THREE).add(BigInteger.ONE); // 合并链式操作
                }
                i++;
            }

            System.out.println("It took " + i + " steps to reach 1. Would you like to do another number? (yes/no)");
            scanner.nextLine(); // 读取nextBigInteger后遗留的换行符
            String yn = scanner.nextLine();

            if (Objects.equals(yn, "no")) {
                repeat = false;
            }
        }
        scanner.close(); // 关闭Scanner释放资源
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:37:32