
本教程详细介绍了如何在Java中实现罗马数字与整数之间的双向转换,特别关注了初学者常遇到的问题,如无限循环、对象状态不一致以及字符串比较的正确性。文章通过逐步分析和代码示例,指导读者使用基本的控制流结构构建一个健壮的转换器,无需依赖数组或映射等高级数据结构,帮助巩固Java编程基础。
在Java中实现罗马数字与整数的转换,通常会封装在一个类中,该类负责存储并管理这两种表示形式。我们定义一个 RomanNumeral 类,包含 romanNum (字符串类型) 和 decimalNum (整数类型) 两个私有成员变量,以及相应的构造函数、getter和setter方法。
package jfauvelle_G10_A04;
public class RomanNumeral {
private String romanNum = "";
private int decimalNum = 0;
// 无参构造函数
public RomanNumeral() {
romanNum = "";
decimalNum = 0;
}
// 接收罗马数字字符串的构造函数
public RomanNumeral(String r) {
// 在构造时进行转换,确保decimalNum也得到初始化
this.romanNum = r;
this.decimalNum = convertRomanToInteger(r);
}
// 接收整数的构造函数
public RomanNumeral(int i) {
// 在构造时进行转换,确保romanNum也得到初始化
this.decimalNum = i;
this.romanNum = convertIntegerToRoman(i);
}
// Getter和Setter方法
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;
}
// ... 转换方法将在后续章节详细介绍
}注意事项:
将整数转换为罗马数字通常采用“贪婪算法”。从最大的罗马数字值开始,只要当前整数大于或等于该值,就将对应的罗马字符添加到结果字符串中,并从整数中减去该值,重复此过程直到整数变为零。
立即学习“Java免费学习笔记(深入)”;
根据本教程的特定规则(例如,4 = IIII, 9 = VIIII,不考虑减法规则),转换逻辑相对直接。
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 循环确保了整数被正确地分解并转换为罗马数字。
将罗马数字字符串转换为整数需要遍历字符串中的每个字符,并根据其代表的数值进行累加。这是初学者最容易出错的部分,特别是循环和条件判断的运用。
在原始代码中,convertRomanToInteger 方法存在两个主要问题:
为了解决上述问题,我们需要进行以下修正:
private int convertRomanToInteger(String n) {
String romanStr = n; // 使用更具描述性的变量名
int finalDecimal = 0;
// 修正:循环条件应为 i < romanStr.length()
for (int i = 0; i < romanStr.length(); i++) {
char currentChar = romanStr.charAt(i); // 获取当前字符
// 修正:将while循环改为if条件判断
if (currentChar == 'M') {
finalDecimal += 1000;
} else if (currentChar == 'D') { // 使用else if 提高效率,避免不必要的判断
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;
}编写测试用例是验证代码正确性的重要步骤。在Java中,比较字符串内容时,应始终使用 .equals() 方法,而不是 == 运算符。== 运算符比较的是两个字符串对象的引用地址,而 .equals() 比较的是它们的内容。
public class RomanNumeralCalculatorTestCase {
public static void main(String[] args) {
boolean working = true;
// 测试空构造函数和setter
RomanNumeral case1 = new RomanNumeral();
case1.setRomanNumeral("XVI"); // 设置罗马数字,内部会转换为十进制
// 修正:字符串比较使用 .equals()
if (!case1.getRomanNumeral().equals("XVI")) {
working = false;
System.err.println("ERROR: Roman numeral was not set properly. It is " + case1.getRomanNumeral()
+ ". It should be XVI");
}
// 验证十进制值是否同步更新
if (case1.getDecimalNumeral() != 16) { // XVI = 16
working = false;
System.err.println("ERROR: Decimal number was not updated properly after setting Roman. It is " + case1.getDecimalNumeral()
+ ". It should be 16");
}
case1.setDecimalNumeral(2004); // 设置十进制,内部会转换为罗马数字
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")) { // 根据本教程规则 2004 = MMIIII
working = false;
System.err.println("ERROR: Roman numeral was not updated properly after setting Decimal. It is " + case1.getRomanNumeral()
+ ". It should be MMIIII");
}
// 测试整数构造函数
RomanNumeral case2 = new RomanNumeral(1000);
String s = "M";
if (!(case2.getRomanNumeral().equals(s))) { // 修正:字符串比较使用 .equals()
working = false;
System.err.println("ERROR: Roman numeral from int constructor is incorrect. It is " + case2.getRomanNumeral()
+ ", it should be M.");
}
if (case2.getDecimalNumeral() != 1000) {
working = false;
System.err.println("ERROR: Decimal number from int constructor 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: Decimal number from string constructor is incorrect. It is " + case3.getDecimalNumeral()
+ ". It should be 1000");
}
if (!case3.getRomanNumeral().equals("M")) { // 修正:字符串比较使用 .equals()
working = false;
System.err.println("ERROR: Roman numeral from string constructor is incorrect. It is " + case3.getRomanNumeral()
+ ". It should be M");
}
if (working)
System.out.print("Congratz ! The test case work !");
}
}通过本教程,我们学习了如何在Java中实现一个基本的罗马数字与整数转换器,并解决了初学者常犯的几个错误:
掌握这些基础知识和常见的编程陷阱,对于编写健壮、可维护的Java代码至关重要。
以上就是Java罗马数字转换器:基础实现与常见陷阱解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号