
本文将深入探讨如何在不使用数组或映射(Map)的情况下,在Java中实现罗马数字与整数之间的双向转换。我们将构建一个`RomanNumeral`类,详细讲解转换逻辑,特别是如何修正常见的无限循环错误,并确保对象内部数据的一致性,以提供一个简洁高效的解决方案。
1. 核心类设计:RomanNumeral
为了实现罗马数字和整数的相互转换,我们首先设计一个RomanNumeral类来封装这两种表示形式及其转换逻辑。该类将包含两个私有成员变量:romanNum(字符串类型,表示罗马数字)和decimalNum(整数类型,表示十进制数)。
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); // 构造时进行转换 } // Setter和Getter方法 public void setRomanNumeral(String r) { this.romanNum = r; this.decimalNum = convertRomanToInteger(r); // 更新罗马数字时,同时更新十进制数 } public String getRomanNumeral() { return romanNum; } public void setDecimalNumeral(int i) { this.decimalNum = i; this.romanNum = convertIntegerToRoman(i); // 更新十进制数时,同时更新罗马数字 } public int getDecimalNumeral() { return decimalNum; } // 转换方法将在后续章节详细介绍 private String convertIntegerToRoman(int r) { // 实现细节 return ""; } private int convertRomanToInteger(String n) { // 实现细节 return 0; }}
注意事项:
在setRomanNumeral和setDecimalNumeral方法中,当设置其中一个值时,务必调用相应的转换方法来更新另一个值,以确保romanNum和decimalNum始终保持一致。这是维护对象内部数据完整性的关键。
2. 整数到罗马数字的转换 (convertIntegerToRoman)
根据本教程的特定规则(例如,4表示为IIII,9表示为VIIII,而不是IV或IX),我们可以采用一种贪婪的减法策略来实现整数到罗马数字的转换。这意味着我们从最大的罗马数字值开始,尽可能多地减去它,然后继续处理下一个较小的值。
立即学习“Java免费学习笔记(深入)”;
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; }
逻辑解析:每个while循环负责处理一个特定的罗马数字符号。只要当前整数值大于或等于该符号对应的数值,就将该符号添加到结果字符串中,并从整数值中减去该数值。这个过程会持续进行,直到整数值无法再减去该符号的数值,然后进入下一个较小符号的处理。由于我们不考虑像IV或IX这样的特殊组合,这种直接的减法策略是完全有效的。
3. 罗马数字到整数的转换 (convertRomanToInteger)
罗马数字到整数的转换需要遍历罗马数字字符串中的每个字符,并将其对应的数值累加起来。这里需要特别注意避免常见的逻辑错误,例如无限循环。
private int convertRomanToInteger(String n) { String roman = n; // 使用更具描述性的变量名 int finalDecimal = 0; // 遍历罗马数字字符串中的每一个字符 // 注意:循环条件应为 i < roman.length(),而不是 i <= roman.length(), // 以避免 IndexOutOfBoundsException。 for (int i = 0; i < roman.length(); i++) { char currentChar = roman.charAt(i); // 获取当前字符 // 使用 if 语句判断当前字符,并累加对应的数值 // 每个字符只会被处理一次,因此不需要 while 循环 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; }
错误修正与逻辑解析:
稿定抠图
AI自动消除图片背景
76 查看详情
无限循环的根源: 原始代码中在for循环内部使用了嵌套的while循环(例如 while (decimal.charAt(i) == ‘M’))。问题在于,decimal.charAt(i)在内部while循环中始终是同一个字符,如果它满足条件,while循环将永远不会终止,因为i(循环索引)没有在内部while循环中递增。正确的做法:if语句: 由于我们处理的是单个字符,每个字符只对应一个特定的数值,并且我们按照从左到右的顺序逐一处理,因此使用if-else if结构是正确的。每个字符在for循环的每次迭代中被检查一次,并将其值累加到finalDecimal中。循环条件修正: for (int i = 0; i < roman.length(); i++) 是正确的循环条件。原始代码中的 i <= decimal.length() 会导致在处理字符串末尾时,尝试访问 decimal.charAt(decimal.length()),这会引发IndexOutOfBoundsException。
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); // 确保数据一致性 } public String getRomanNumeral() { return romanNum; } public void setDecimalNumeral(int i) { this.decimalNum = i; this.romanNum = convertIntegerToRoman(i); // 确保数据一致性 } 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 roman = n; int finalDecimal = 0; for (int i = 0; i < roman.length(); i++) { // 修正循环条件 char currentChar = roman.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方法进行测试。
public class RomanNumeralCalculatorTestCase { public static void main(String[] args) { boolean working = true; // 测试默认构造函数和Setter RomanNumeral case1 = new RomanNumeral(); case1.setRomanNumeral("XVI"); // 应该同时更新 decimalNum 为 16 if (!"XVI".equals(case1.getRomanNumeral())) { // 使用 .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"); } if (!"MMIIII".equals(case1.getRomanNumeral())) { // 验证 romanNum 是否正确更新 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 constructor failed. Roman is " + case2.getRomanNumeral() + ", it should be M."); } if (case2.getDecimalNumeral() != 1000) { working = false; System.err.println("ERROR: Decimal number constructor failed. Decimal is " + case2.getDecimalNumeral() + ", it should be 1000."); } // 测试字符串构造函数 RomanNumeral case3 = new RomanNumeral("M"); if (case3.getDecimalNumeral() != 1000) { working = false; System.err.println("ERROR: Roman numeral constructor failed. Decimal is " + case3.getDecimalNumeral() + ". It should be 1000"); } if (!"M".equals(case3.getRomanNumeral())) { working = false; System.err.println("ERROR: Roman numeral constructor failed. Roman is " + case3.getRomanNumeral() + ". It should be M"); } // 测试其他转换,例如 4 和 9 RomanNumeral case4 = new RomanNumeral(4); if (!"IIII".equals(case4.getRomanNumeral())) { working = false; System.err.println("ERROR: Conversion for 4 failed. Got " + case4.getRomanNumeral() + ", expected IIII."); } RomanNumeral case5 = new RomanNumeral("IIII"); if (case5.getDecimalNumeral() != 4) { working = false; System.err.println("ERROR: Conversion for IIII failed. Got " + case5.getDecimalNumeral() + ", expected 4."); } RomanNumeral case6 = new RomanNumeral(9); if (!"VIIII".equals(case6.getRomanNumeral())) { working = false; System.err.println("ERROR: Conversion for 9 failed. Got " + case6.getRomanNumeral() + ", expected VIIII."); } RomanNumeral case7 = new RomanNumeral("VIIII"); if (case7.getDecimalNumeral() != 9) { working = false; System.err.println("ERROR: Conversion for VIIII failed. Got " + case7.getDecimalNumeral() + ", expected 9."); } if (working) { System.out.print("Congratz ! The test cases work !"); } }}
测试注意事项:
在Java中比较字符串内容时,应使用equals()方法而不是==运算符,因为==比较的是对象的引用。测试用例应覆盖所有关键功能,包括构造函数、setter方法以及整数到罗马数字和罗马数字到整数的转换。
6. 总结
本教程展示了如何在不使用Java中的数组或映射数据结构的情况下,实现罗马数字与整数的相互转换。关键要点包括:
类设计: RomanNumeral类封装了罗马数字和十进制数的表示,并通过构造函数和setter方法实现两者之间的自动转换。数据一致性: 在set方法中,确保当一个值被更新时,另一个相关值也通过转换方法同步更新,以保持对象内部状态的逻辑一致性。整数转罗马数字: 采用贪婪减法策略,通过一系列while循环从大到小处理罗马数字的各个值,构建最终的罗马数字字符串。罗马数字转整数: 遍历罗马数字字符串中的每个字符,使用if-else if结构判断字符并累加其对应的数值。关键在于避免使用嵌套的while循环,因为这会导致无限循环;每个字符只需处理一次。 同时,确保for循环的条件是i < length以避免IndexOutOfBoundsException。特定规则: 本实现严格遵循了4表示为IIII,9表示为VIIII的简化规则,因此不需要处理IV、IX等特殊减法表示。
通过遵循这些原则,即使在资源受限或特定学习阶段(例如尚未学习数组和映射)下,也能构建出功能正确且逻辑清晰的罗马数字转换器。
以上就是Java中不使用数组实现罗马数字与整数的相互转换的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1025071.html
微信扫一扫
支付宝扫一扫