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

如何编写Java程序输出指定范围(100-150)内各位数字均能被3整除的数?解决无限循环

解决Java程序无限循环+查找各位数字均能被3整除的数

嘿,我来帮你搞定这个无限循环的坑!首先得说,你遇到的无限循环几乎都是因为循环变量没正确更新或者循环条件写反了,咱们一步步来解决。

先揪出无限循环的常见原因

最容易踩的坑就是用while循环时,忘了给循环变量加递增/递减操作,比如:

int num = 100;
while (num <= 150) {
    // 这里写检查各位数字的代码
    // 忘了写 num++; !!!
}

这样num永远是100,num <=150的条件永远成立,自然就无限循环了。

还有一种情况是for循环的条件写错,比如把递增写成递减:

for (int num = 100; num <=150; num--) {
    // 代码
}

num会越来越小,永远满足num <=150,也会无限循环。

正确的代码实现

我给你写一个不会踩坑的版本,用for循环(自带变量更新,不容易忘),同时实现查找各位数字均能被3整除的逻辑:

public class ValidNumbersFinder {
    public static void main(String[] args) {
        int start = 100;
        int end = 150;
        
        // 遍历指定范围的每个数
        for (int num = start; num <= end; num++) {
            // 分解百位、十位、个位
            int hundreds = num / 100;
            int tens = (num / 10) % 10;
            int units = num % 10;
            
            // 检查各位是否都能被3整除
            if (hundreds % 3 == 0 && tens % 3 == 0 && units % 3 == 0) {
                System.out.println("符合条件的数:" + num);
            }
        }
    }
}

额外说明:关于你指定的100-150范围

悄悄说一句,这个区间里没有符合条件的数!因为所有数的百位都是1,1除以3余1,不满足“各位数字均能被3整除”的要求。如果想测试程序是否正常,可以把范围改成300-399,这样百位是3(能被3整除),就能输出一堆符合条件的数啦,比如300、303、306等等。

用while循环的正确写法

如果你偏爱while循环,一定要记得手动更新循环变量:

public class ValidNumbersFinderWhile {
    public static void main(String[] args) {
        int num = 100;
        int end = 150;
        
        while (num <= end) {
            int hundreds = num / 100;
            int tens = (num / 10) % 10;
            int units = num % 10;
            
            if (hundreds % 3 == 0 && tens % 3 == 0 && units % 3 == 0) {
                System.out.println("符合条件的数:" + num);
            }
            
            num++; // 这行必须加!否则无限循环
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:45:21