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

Java使用模运算与整数除法实现银行账号校验的问题求助

问题排查

你的代码存在两处核心逻辑错误,与校验规则不符:

  • 遗漏最右侧第一位校验位的累加:你通过account % 10提取了最右侧的第一位数字,但未将其加入总和sum中。
  • 非校验位翻倍逻辑错误:规则要求从右数第二位开始每隔一位翻倍,你当前代码对右数第2、3、4...所有位都执行了翻倍操作,不符合要求。

修正后的实现方案

你可以直接通过循环处理数字本身,不需要额外转字符串判断长度,完全符合规则要求的模运算、整数除法操作规范,还兼容带空格的输入格式:

import javax.swing.JOptionPane;

public class BankAccountValidator {
    public static void main(String[] args) {
        // 自动去除输入中的空格,兼容带分隔空格的账号输入
        String input = JOptionPane.showInputDialog(null, "Enter account number: ").replaceAll("\\s", "");
        long account = Long.parseLong(input);
        int sum = 0;
        // 最右侧第一位不需要翻倍,初始翻倍标记设为false
        boolean needDouble = false;

        while (account > 0) {
            long digit = account % 10;
            account /= 10;

            if (needDouble) {
                digit *= 2;
                if (digit > 9) {
                    digit -= 9;
                }
            }
            sum += digit;
            // 切换下一位的翻倍状态
            needDouble = !needDouble;
        }

        if (sum % 10 != 0) {
            JOptionPane.showMessageDialog(null, "Account number invalid");
        } else {
            JOptionPane.showMessageDialog(null, "Account number valid");
        }
        JOptionPane.showMessageDialog(null, "校验总和为:" + sum);
    }
}

测试账号校验结果

按规则计算两个测试账号的校验结果如下:

  • 5113 4765 12:校验总和为34,末位不为0,账号无效
  • 65 1234 1234:校验总和为36,末位不为0,账号无效

你之前代码仅返回一个账号有效,正是逻辑错误导致的计算结果偏差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:54:04