Java无数组Map罗马数转换教程
时间:2025-11-25 20:12:42 465浏览 收藏
知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个文章开发实战,手把手教大家学习《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) 的修正
这是原始代码中存在无限循环问题的关键部分。
3.1 问题分析
原始的convertRomanToInteger方法在一个for循环内部,对每个字符使用了多个while循环进行判断:
// 原始代码片段(存在问题)
for (int i = 0; i <= decimal.length(); i++) { // 循环边界也存在问题
while (decimal.charAt(i) == 'M') { // 如果当前字符是'M',这里会无限循环
finalDecimal += 1000;
}
// ... 其他while循环
}问题在于:
- 无限循环: while (decimal.charAt(i) == 'M')这个条件一旦为真,i的值在while循环内部不会改变,decimal.charAt(i)的值也因此不会改变。这将导致while循环条件永远为真,程序陷入死循环。
- 循环边界错误: 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语句。
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中罗马数字与整数的相互转换。关键的修正点在于:
- 消除无限循环: 将convertRomanToInteger方法中,for循环内部的while语句改为if-else if链,确保每个字符只被处理一次。
- 修正循环边界: 将for循环的条件从i <= length()修正为i < length(),避免IndexOutOfBoundsException。
- 保持对象状态一致性: 修改setRomanNumeral和setDecimalNumeral方法,使其在更新一个字段时,自动转换并更新另一个相关字段,从而保证RomanNumeral对象内部数据的一致性。
此实现严格遵循了不使用数组和Map的限制,展示了基础控制流和字符串操作在解决这类问题中的应用。需要注意的是,本实现基于简化的罗马数字规则(例如,4=IIII,9=VIIII),不包含标准罗马数字中的减法规则(如IV、IX等)。如果需要支持标准规则,convertRomanToInteger方法将需要更复杂的逻辑来处理字符组合。此外,对于输入非法罗马字符的字符串,当前实现会忽略或产生不准确的结果,可以在convertRomanToInteger中添加错误处理机制来增强健壮性。
到这里,我们也就讲完了《Java无数组Map罗马数转换教程》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
362 收藏
-
350 收藏
-
225 收藏
-
488 收藏
-
216 收藏
-
447 收藏
-
121 收藏
-
347 收藏
-
299 收藏
-
226 收藏
-
480 收藏
-
161 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习