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

Java循环输出异常排查:printCount与printWhileCount逻辑问题求助

问题排查与修正

错误原因

你的代码核心问题是输出时额外多加上了参数n:

  • 当num能被2整除时,你写了(num / 2) + n,但规则要求输出的是num的1/2,也就是num / 2
  • 其余情况你写了num + n,但规则要求直接输出num本身

修正后的代码

public class HelloPrinter {
    public static void main(String[] args) {
        printCount(5);
        printCountWhile(5);
    }

    public static void printCount(int n) {
        for (int i = 0; i < 10; i++) {
            int num = i + n;
            if (num % 2 == 0) {
                System.out.print((num / 2) + " ");
            } else if (num % 3 == 0) {
                System.out.print("0 ");
            } else {
                System.out.print(num + " ");
            }
        }
        System.out.println();
    }

    public static void printCountWhile(int n) {
        int i = 0;
        while (i < 10) {
            int num = i + n;
            if (num % 2 == 0) {
                System.out.print((num / 2) + " ");
            } else if (num % 3 == 0) {
                System.out.print("0 ");
            } else {
                System.out.print(num + " ");
            }
            i++;
        }
        System.out.println();
    }
}

验证结果

运行修正后的代码,传入参数5时,两个方法都会输出预期的:5 1 6 0 7 5 8 7 9 0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 06:12:33