java - 将 Int 转换为罗马数字

标签 java

我的代码遇到问题。请帮助。这是到目前为止我的代码,我需要使用方法。它需要能够获取 1-3999 之间的整数并将其转换为罗马数字。有没有比我所做的更简单的方法?

    public static void main(String[] args) {
    Scanner in = new Scanner (System.in);
    System.out.print("Enter a number between 1 and 3999 (0 to quit): ");
    int input = in.nextInt();
    while (input !=0 )
    {
        if(input < 0 || input > 3999){
        System.out.println("ERROR! NUmber must be between 1 and 3999 (0 to quit): ");
        System.out.print("Enter a number between 1 and 3999 (0 to quit): ");
        input = in.nextInt();
        }
        else if(input > 0){
        String roman = convertNumberToNumeral(input);
        System.out.println("The number " + input + " is the Roman numberal " + roman);
        System.out.print("Enter a number between 1 and 3999 (0 to quit): ");
        input = in.nextInt();
        }
    }
    while (input == 0)
    {
        break;
    }
        System.out.println("Goodbye!");
}

// Given a Scanner as input, prompts the user to input a number between 1 and 3999.
// Checks to make sure the number is within range, and provides an error message until
// the user provides a value within range.  Returns the number input by the user to the
// calling program.
private static int promptUserForNumber(Scanner inScanner, int input) {
}

// Given a number as input, converts the number to a String in Roman numeral format, 
// following the rules in the writeup for Lab 09.  Returns the String to the calling
// program.  NOTE:  This method can possibly get long and complex.  Use the 
// convertDigitToNumeral method below to break this up and make it a bit simpler to code.
private static String convertNumberToNumeral(int input) {
    String romanOnes = ("");
    String romanTens = ("");
    String romanHundreds = ("");
    String romanThousands = ("");
    int ones = input % 10;
    int tens2 = input / 10;
    if (tens2 < 10)
    {
        tens2 = input / 10;
    }
    else {
        tens2 = tens2 % 100;
    }
    int tens = tens2;

    int hundreds2 = input / 100;
    if (hundreds2 < 10)
    {
        hundreds2 = input / 10;
    }
    else {
        hundreds2 = hundreds2 % 1000;
    }

    int hundreds = hundreds2;

    int thousands2 = input / 1000;
    if (thousands2 < 10)
    {
        thousands2 = input / 10;
    }
    else {
        thousands2 = thousands2 % 10000;
    }

    int thousands = input & 10000;
    {
        if (ones == 0)
        {
            romanOnes = ("");
        }
        else if (ones == 1)
        {
            romanOnes = ("I");
        }
        else if (ones == 2)
        {
            romanOnes = ("II");
        }
        else if(ones == 3)
        {
            romanOnes = ("III");
        }
        else if(ones == 4)
        {
            romanOnes = ("IV");
        }
        else if(ones == 5)
        {
            romanOnes = ("V");
        }
        else if(ones == 6)
        {
            romanOnes = ("VI");
        }
        else if(ones == 7)
        {
            romanOnes = ("VII");
        }
        else if(ones == 8)
        {
            romanOnes = ("VIII");
        }
        else if(ones == 9)
        {
            romanOnes = ("IX");
        }
    }
    {
        if (tens == 0)
        {
            romanTens = ("");
        }
        else if (tens == 1)
        {
            romanTens = ("X");
        }
        else if (tens == 2)
        {
            romanTens = ("XX");
        }
        else if(tens == 3)
        {
            romanTens = ("XXX");
        }
        else if(tens == 4)
        {
            romanTens = ("XL");
        }
        else if(tens == 5)
        {
            romanTens = ("L");
        }
        else if(tens == 6)
        {
            romanTens = ("LX");
        }
        else if(tens == 7)
        {
            romanTens = ("LXX");
        }
        else if(tens == 8)
        {
            romanTens = ("LXXX");
        }
        else if(tens == 9)
        {
            romanTens = ("XC");
        }
    }
    {
        if (hundreds == 0)
        {
            romanHundreds = ("");
        }
        else if (hundreds == 1)
        {
            romanHundreds = ("C");
        }
        else if (hundreds == 2)
        {
            romanHundreds = ("CC");
        }
        else if(hundreds == 3)
        {
            romanHundreds = ("CCC");
        }
        else if(hundreds == 4)
        {
            romanHundreds = ("CD");
        }
        else if(hundreds == 5)
        {
            romanHundreds = ("D");
        }
        else if(hundreds == 6)
        {
            romanHundreds = ("DC");
        }
        else if(hundreds == 7)
        {
            romanHundreds = ("DCC");
        }
        else if(hundreds == 8)
        {
            romanHundreds = ("DCCC");
        }
        else if(hundreds == 9)
        {
            romanHundreds = ("CM");
        }
    }
    {
        if (thousands == 0)
        {
            romanThousands = ("");
        }
        else if (thousands == 1)
        {
            romanThousands = ("M");
        }
        else if (thousands == 2)
        {
            romanThousands = ("MM");
        }
        else if(thousands == 3)
        {
            romanThousands = ("MMM");
        }
    }
    String roman = (romanThousands + romanHundreds + romanTens + romanOnes);
    return roman;

}

// Given a digit and the Roman numerals to use for the "one", "five" and "ten" positions,
// returns the appropriate Roman numeral for that digit.  For example, if the number to
// convert is 49 we would call convertDigitToNumeral twice.  The first call would be:
//     convertDigitToNumeral(9, 'I','V','X')
// and would return a value of "IX".  The second call would be:
//     convertDigitToNumeral(4, 'X','L','C')
// and would return a value of "XL".  Putting those togeter we would see that 49 would be the
// Roman numeral XLIX.
// Call this method from convertNumberToNumeral above to convert an entire number into a 
// Roman numeral.
private static String convertDigitToNumeral(int digit, char one, char five, char ten) {


}

最佳答案

哇!你似乎把这种方式搞得太复杂了。 4clojure.com 上有一个非常相似的问题:Write Roman Numerals 。这里有一些额外的错误检查逻辑,但即便如此,您也不应该需要这么多代码。我用 Clojure 中的 10 行函数解决了这个问题。然而,考虑到大多数人对 Lisps 不太满意,我将为您提供一个从 Clojure 解决方案快速翻译而来的 Python 解决方案。

def to_roman(n):
  digits = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD' ),
            (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'),
            (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
  result = ""
  while len(digits) > 0:
    (val, romn) = digits[0] # Unpacks the first pair in the list
    if n < val:
      digits.pop(0) # Removes first element
    else:
      n -= val
      result += romn
  return result

Python 的语法足以像伪代码一样,即使您实际上并不了解 Python,也可能可以理解它。我将把它翻译成 Java。

<小时/>

回复您的评论:

I think my problem is using the methods, how I do it using the methods I have listed?

对你的方法的注释非常清楚它们应该做什么。您需要使用 Scanner 移动所有代码来自main进入promptUserForNumber 。您可以调用promptUserForNumber来自main获取有效的输入数字。

获得号码后,将其传递给 convertNumberToNumeral来处理转换。 convertNumberToNumeral应该循环号码的每个数字并调用 convertDigitToNumeral将每个数字转换为相应的罗马数字字符串。之后concatenating所有数字组件一起convertNumberToNumeral可以返回完整的罗马数字表示字符串作为结果。

convertDigitToNumeral的逻辑几乎与 to_roman 相同我在上面发布的解决方案,但你只需要处理一个数字。它看起来像这样:

def digit2roman(n, ten, five, one):
  digits = [(9, one+ten), (5, five), (4, one+five), (1, one)]
  result = ""
  while len(digits) > 0:
    val, romn = digits[0]
    if n < val:
      digits.pop(0)
    else:
      n -= val
      result += romn
  return result

拆分digits分成 2 个列表可能会使它更容易转换为 Java:

def digit2roman(n, ten, five, one):
  digitsV = [9, 5, 4, 1]
  digitsR = [one+ten, five, one+five, one]
  result = ""
  i = 0
  while i < len(digitsV):
    if n < digitsV[i]:
      i += 1
    else:
      n -= digitsV[i]
      result += digitsR[i]
  return result

在高级语言中,当您想要同时迭代 2 个序列时,通常会将两个序列压缩为单个序列对,但在 Java 中,您通常只迭代索引。您应该可以轻松地使用 Java 数组转换此代码。

关于java - 将 Int 转换为罗马数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17479287/

相关文章:

java - 如何为 sourceforge 的开源项目配置环境

java - 有人可以解释这个java代码吗

java - Sitebricks HTML 文件

java - 动态条件代码注入(inject)java文件

java - 如何在 Android 中为动态选择的图像创建 savedInstanceState?

java - 使用嵌套 for 循环的简单 Java 金字塔

java - 列表迭代器返回零

java - jbpm 6 - 示例 Web 应用程序 "rewards-basic"错误

java - 正则表达式将所有内容匹配到空行

java - 在Java中将函数作为参数传递给方法并返回其返回值?