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

Java程序问题:正负数值范围遍历及因子终止条件失效排查

问题分析

你的代码在处理负数范围时存在两个核心问题:

  1. 除零异常隐患:当start递增到0时,end%start会触发ArithmeticException,导致程序崩溃。
  2. 逻辑与需求不匹配:你期望在遇到能整除起始值的数时终止循环,但代码中判断的是end%start ==0,这只有当start等于end时才会成立(负数场景下还会触发除零问题),完全不符合你描述的需求。
修复方案

下面的代码会同时解决这两个问题,确保正负数值场景下行为一致:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int startNum = 0;
        int endNum = 0;

        System.out.print("Enter starting: ");
        startNum = input.nextInt();
        System.out.print("Enter ending: ");
        endNum = input.nextInt();

        int current = startNum;
        // 根据起始和结束值确定遍历步长,支持正向和反向遍历
        int step = startNum <= endNum ? 1 : -1;

        // 通用循环条件,适配正负范围
        while ((step == 1 && current <= endNum) || (step == -1 && current >= endNum)) {
            System.out.println(current);
            int nextCurrent = current + step;
            
            // 先判断下一个数是否为0,避免除零错误
            if (nextCurrent != 0 && startNum % nextCurrent == 0) {
                System.out.println(nextCurrent);
                break;
            }
            current = nextCurrent;
        }
    }
}
关键改进点
  • 动态步长:根据startNum和endNum的大小关系自动选择步长(1或-1),支持正向和反向遍历,适配所有数值范围。
  • 除零防护:在取模前先检查下一个数是否为0,避免触发除零异常。
  • 修正判断逻辑:将判断条件改为startNum % nextCurrent ==0,匹配你描述的需求——当遇到第一个能整除起始值的数时终止循环。
测试验证
  • 输入-10和-1:输出-10、-9、-8、-7、-6、-5后终止,符合你的预期。
  • 输入10和1:输出10、9、8、7、6、5后终止,正负场景行为一致。
  • 输入5和10:输出5、6、7、8、9、10后终止(因为10能整除5)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:30:16