首页 > Java > java教程 > 正文

Java中不使用数组和Map实现罗马数字与整数的相互转换教程

聖光之護
发布: 2025-11-18 14:17:02
原创
148人浏览过

Java中不使用数组和Map实现罗马数字与整数的相互转换教程

本教程详细指导如何在java中不依赖数组和map实现罗马数字与整数的相互转换。我们将重点解决原始代码中罗马数字转整数时出现的无限循环问题,通过将内部while循环改为if判断,并确保对象状态在设置时保持一致,从而构建一个功能完善且易于理解的romannumeral类。

1. RomanNumeral 类结构概览

首先,我们定义一个RomanNumeral类,它包含两个核心私有成员:romanNum(罗马数字字符串表示)和decimalNum(整数表示)。为了提供灵活的初始化方式,类中设计了三个构造函数:一个无参构造函数、一个接受字符串作为罗马数字的构造函数,以及一个接受整数作为十进制数的构造函数。此外,还提供了相应的getter和setter方法来访问和修改这些内部状态。

package jfauvelle_G10_A04;

public class RomanNumeral {
    private String romanNum = "";
    private int decimalNum = 0;

    // 无参构造函数
    public RomanNumeral() {
        this.romanNum = "";
        this.decimalNum = 0;
    }

    // 接受罗马数字字符串的构造函数
    public RomanNumeral(String r) {
        this.romanNum = r;
        this.decimalNum = convertRomanToInteger(r); // 自动转换并设置十进制值
    }

    // 接受整数的构造函数
    public RomanNumeral(int i) {
        this.decimalNum = i;
        this.romanNum = convertIntegerToRoman(i); // 自动转换并设置罗马数字字符串
    }

    // Getter和Setter方法 (部分需要修正以确保状态一致性)
    public String getRomanNumeral() {
        return romanNum;
    }

    public int getDecimalNumeral() {
        return decimalNum;
    }

    // 修正后的Setter方法,确保内部状态一致
    public void setRomanNumeral(String r) {
        this.romanNum = r;
        this.decimalNum = convertRomanToInteger(r); // 当设置罗马数字时,同步更新十进制值
    }

    public void setDecimalNumeral(int i) {
        this.decimalNum = i;
        this.romanNum = convertIntegerToRoman(i); // 当设置十进制值时,同步更新罗马数字
    }

    // ... 转换方法将在后续部分实现
}
登录后复制

2. 整数到罗马数字的转换 (convertIntegerToRoman)

将整数转换为罗马数字的逻辑相对直观。由于本教程遵循简化规则(例如,4表示为IIII而非IV,9表示为VIIII而非IX),我们只需从最大的罗马数字值开始,贪婪地减去对应的整数,并拼接其罗马字符,直到整数变为0。

    public String convertIntegerToRoman(int r) {
        int roman = r;
        String finalRoman = "";

        // 从大到小依次处理罗马数字
        while (roman >= 1000) {
            finalRoman = finalRoman + "M";
            roman -= 1000;
        }

        while (roman >= 500) {
            finalRoman = finalRoman + "D";
            roman -= 500;
        }

        while (roman >= 100) {
            finalRoman = finalRoman + "C";
            roman -= 100;
        }

        while (roman >= 50) {
            finalRoman = finalRoman + "L";
            roman -= 50;
        }

        while (roman >= 10) {
            finalRoman = finalRoman + "X";
            roman -= 10;
        }

        while (roman >= 5) {
            finalRoman = finalRoman + "V";
            roman -= 5;
        }

        while (roman >= 1) {
            finalRoman = finalRoman + "I";
            roman -= 1;
        }

        return finalRoman;
    }
登录后复制

此方法在原始代码中已经正确实现,并且能够很好地处理简化规则下的整数到罗马数字转换。

3. 罗马数字到整数的转换 (convertRomanToInteger) 的修正

这是原始代码中存在无限循环问题的关键部分。

立即学习Java免费学习笔记(深入)”;

3.1 问题分析

原始的convertRomanToInteger方法在一个for循环内部,对每个字符使用了多个while循环进行判断:

// 原始代码片段(存在问题)
for (int i = 0; i <= decimal.length(); i++) { // 循环边界也存在问题
    while (decimal.charAt(i) == 'M') { // 如果当前字符是'M',这里会无限循环
        finalDecimal += 1000;
    }
    // ... 其他while循环
}
登录后复制

问题在于:

  1. 无限循环: while (decimal.charAt(i) == 'M')这个条件一旦为真,i的值在while循环内部不会改变,decimal.charAt(i)的值也因此不会改变。这将导致while循环条件永远为真,程序陷入死循环。
  2. 循环边界错误: for (int i = 0; i <= decimal.length(); i++) 应该改为 for (int i = 0; i < decimal.length(); i++)。当i等于decimal.length()时,decimal.charAt(i)会抛出IndexOutOfBoundsException。

3.2 解决方案

正确的做法是,for循环负责遍历罗马数字字符串的每一个字符。在每次迭代中,我们只需要判断当前字符是什么,然后根据其值累加到总的十进制数中。因此,内部的while循环应该改为if语句。

怪兽AI数字人
怪兽AI数字人

数字人短视频创作,数字人直播,实时驱动数字人

怪兽AI数字人 44
查看详情 怪兽AI数字人
    private int convertRomanToInteger(String n) {
        String romanString = n; // 更名为romanString以避免混淆
        int finalDecimal = 0;

        // 遍历罗马数字字符串的每一个字符
        // 注意:循环条件应为 i < romanString.length()
        for (int i = 0; i < romanString.length(); i++) {
            char currentChar = romanString.charAt(i); // 获取当前字符

            // 使用if语句判断当前字符并累加对应的值
            if (currentChar == 'M') {
                finalDecimal += 1000;
            } else if (currentChar == 'D') {
                finalDecimal += 500;
            } else if (currentChar == 'C') {
                finalDecimal += 100;
            } else if (currentChar == 'L') {
                finalDecimal += 50;
            } else if (currentChar == 'X') {
                finalDecimal += 10;
            } else if (currentChar == 'V') {
                finalDecimal += 5;
            } else if (currentChar == 'I') {
                finalDecimal += 1;
            }
            // 如果遇到不识别的字符,此处可添加错误处理逻辑
        }
        return finalDecimal;
    }
登录后复制

通过将while改为if,并修正for循环的边界,我们确保了每个字符只被处理一次,并且循环能够正常终止。

4. 完整的 RomanNumeral 类实现

整合上述修正后,RomanNumeral类的完整代码如下:

package jfauvelle_G10_A04;

public class RomanNumeral {
    private String romanNum = "";
    private int decimalNum = 0;

    public RomanNumeral() {
        this.romanNum = "";
        this.decimalNum = 0;
    }

    public RomanNumeral(String r) {
        this.romanNum = r;
        this.decimalNum = convertRomanToInteger(r);
    }

    public RomanNumeral(int i) {
        this.decimalNum = i;
        this.romanNum = convertIntegerToRoman(i);
    }

    public void setRomanNumeral(String r) {
        this.romanNum = r;
        this.decimalNum = convertRomanToInteger(r); // 确保decimalNum同步更新
    }

    public String getRomanNumeral() {
        return romanNum;
    }

    public void setDecimalNumeral(int i) {
        this.decimalNum = i;
        this.romanNum = convertIntegerToRoman(i); // 确保romanNum同步更新
    }

    public int getDecimalNumeral() {
        return decimalNum;
    }

    public String convertIntegerToRoman(int r) {
        int roman = r;
        String finalRoman = "";

        while (roman >= 1000) {
            finalRoman = finalRoman + "M";
            roman -= 1000;
        }

        while (roman >= 500) {
            finalRoman = finalRoman + "D";
            roman -= 500;
        }

        while (roman >= 100) {
            finalRoman = finalRoman + "C";
            roman -= 100;
        }

        while (roman >= 50) {
            finalRoman = finalRoman + "L";
            roman -= 50;
        }

        while (roman >= 10) {
            finalRoman = finalRoman + "X";
            roman -= 10;
        }

        while (roman >= 5) {
            finalRoman = finalRoman + "V";
            roman -= 5;
        }

        while (roman >= 1) {
            finalRoman = finalRoman + "I";
            roman -= 1;
        }
        return finalRoman;
    }

    private int convertRomanToInteger(String n) {
        String romanString = n;
        int finalDecimal = 0;

        for (int i = 0; i < romanString.length(); i++) { // 修正循环边界
            char currentChar = romanString.charAt(i);

            if (currentChar == 'M') {
                finalDecimal += 1000;
            } else if (currentChar == 'D') {
                finalDecimal += 500;
            } else if (currentChar == 'C') {
                finalDecimal += 100;
            } else if (currentChar == 'L') {
                finalDecimal += 50;
            } else if (currentChar == 'X') {
                finalDecimal += 10;
            } else if (currentChar == 'V') {
                finalDecimal += 5;
            } else if (currentChar == 'I') {
                finalDecimal += 1;
            }
        }
        return finalDecimal;
    }
}
登录后复制

5. 测试与验证

为了验证RomanNumeral类的功能,我们可以使用一个简单的main方法进行测试。此测试用例检查了构造函数、setter方法以及转换逻辑的正确性。

public class RomanNumeralCalculatorTestCase {

    public static void main(String[] args) {
        boolean working = true;

        // 测试无参构造函数和Setter方法
        RomanNumeral case1 = new RomanNumeral();
        case1.setRomanNumeral("XVI"); // 设置罗马数字,decimalNum应自动更新为16
        if (!case1.getRomanNumeral().equals("XVI")) { // 使用.equals()比较字符串
            working = false;
            System.err.println("ERROR: Roman numeral was not set properly. It is " + case1.getRomanNumeral()
                    + ". It should be XVI");
        }
        if (case1.getDecimalNumeral() != 16) { // 验证decimalNum是否正确更新
            working = false;
            System.err.println("ERROR: Decimal number was not updated properly. It is " + case1.getDecimalNumeral()
                    + ". It should be 16");
        }

        case1.setDecimalNumeral(2004); // 设置十进制数,romanNum应自动更新为MMIIII
        if (case1.getDecimalNumeral() != 2004) {
            working = false;
            System.err.println("ERROR: Decimal number was not set properly. It is " + case1.getDecimalNumeral()
                    + ". It should be 2004");
        }
        // 根据简化规则,2004应为MMIIII
        if (!case1.getRomanNumeral().equals("MMIIII")) {
            working = false;
            System.err.println("ERROR: Roman numeral was not updated properly. It is " + case1.getRomanNumeral()
                    + ". It should be MMIIII");
        }


        // 测试整数构造函数
        RomanNumeral case2 = new RomanNumeral(1000);
        String s = "M";
        if (!(case2.getRomanNumeral().equals(s))) {
            working = false;
            System.err.println("ERROR: Decimal number was not converted to Roman properly. It is " + case2.getRomanNumeral()
                    + ", it should be M.");
        }
        if (case2.getDecimalNumeral() != 1000) {
            working = false;
            System.err.println("ERROR: Decimal number in case2 is incorrect. It is " + case2.getDecimalNumeral()
                    + ". It should be 1000");
        }


        // 测试字符串构造函数
        RomanNumeral case3 = new RomanNumeral("M");
        if (case3.getDecimalNumeral() != 1000) {
            working = false;
            System.err.println("ERROR: Roman numeral was not converted to Decimal properly. It is " + case3.getDecimalNumeral()
                    + ". It should be 1000");
        }
        if (!case3.getRomanNumeral().equals("M")) {
            working = false;
            System.err.println("ERROR: Roman numeral in case3 is incorrect. It is " + case3.getRomanNumeral()
                    + ". It should be M");
        }


        if (working)
            System.out.print("Congratz ! The test case work !");
        else
            System.err.println("One or more test cases failed.");

    }
}
登录后复制

注意: 在Java中比较字符串内容应使用.equals()方法,而不是==运算符。上述测试用例已修正此细节。

6. 总结与注意事项

通过本教程,我们成功地在不使用数组和Map的情况下,实现了Java中罗马数字与整数的相互转换。关键的修正点在于:

  1. 消除无限循环: 将convertRomanToInteger方法中,for循环内部的while语句改为if-else if链,确保每个字符只被处理一次。
  2. 修正循环边界: 将for循环的条件从i <= length()修正为i < length(),避免IndexOutOfBoundsException。
  3. 保持对象状态一致性: 修改setRomanNumeral和setDecimalNumeral方法,使其在更新一个字段时,自动转换并更新另一个相关字段,从而保证RomanNumeral对象内部数据的一致性。

此实现严格遵循了不使用数组和Map的限制,展示了基础控制流和字符串操作在解决这类问题中的应用。需要注意的是,本实现基于简化的罗马数字规则(例如,4=IIII,9=VIIII),不包含标准罗马数字中的减法规则(如IV、IX等)。如果需要支持标准规则,convertRomanToInteger方法将需要更复杂的逻辑来处理字符组合。此外,对于输入非法罗马字符的字符串,当前实现会忽略或产生不准确的结果,可以在convertRomanToInteger中添加错误处理机制来增强健壮性。

以上就是Java中不使用数组和Map实现罗马数字与整数的相互转换教程的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号