【问题标题】:Converting Roman Numerals to Integers in Java [duplicate]在Java中将罗马数字转换为整数[重复]
【发布时间】:2015-07-21 00:52:46
【问题描述】:

我的导师给了我一个挑战,让用户输入一个数字或罗马数字,然后让程序将其转换为另一个。我已经使它能够将整数转换为罗马数字,但我不知道如何反过来。我曾尝试寻求帮助,但对我的情况没有任何帮助。你们中的一些人可能给了我链接或说这是重复的,但是,我知道如何进行转换(是的,我在这个问题上犯了一个 HUGE 错误)。我的问题是能够同时做到这两点。我不知道如何让它变成这样:哦,你输入了一个整数,把它转换成罗马数字,它也变成这样:哦,罗马数字时间!将其转换为整数。 请帮忙!!

import java.util.Scanner;

public class DecimalRoman {
@SuppressWarnings("resource")
public static void main(String args[]) {
    System.out.print("Enter a Number: ");
    Decimal2Roman();
}

public static void Decimal2Roman() {
    Scanner scan = new Scanner(System.in);
    int num = scan.nextInt();
    if(num>0 && num<4000) //checking whether the number entered is within the range [1-3999]
    {

        /*Saving the Roman equivalent of the thousand, hundred, ten and units place of a decimal number*/
        String thou[]={"","M","MM","MMM"};
        String hund[]={"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
        String ten[]={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
        String unit[]={"","I","II","III","IV","V","VI","VII","VIII","IX"};

        /*Finding the digits in the thousand, hundred, ten and units place*/
        int th=num/1000;
        int h=(num/100)%10;
        int t=(num/10)%10;
        int u=num%10;

        /*Displaying equivalent roman number*/
        System.out.println("The Roman Numeral of " + num + " is " + thou[th]+hund[h]+ten[t]+unit[u]);
    }

    /*Displaying an error message if the number entered is out of range*/
    else
        System.out.println("\nYou entered a number out of Range.\nPlease enter a number in the range [1-3999]");
}
}

【问题讨论】:

    标签: java integer roman-numerals


    【解决方案1】:

    根据您上次的编辑,要识别您获得的输入类型,您可以使用 Scanner.hasNextInt() 方法:

    Scanner scan = new Scanner(System.in);
    if (scan.hasNextInt()) {
        int arabicNumber = scan.nextInt();
    } else {
        String romanNumber = scan.next();
    }
    

    【讨论】:

    • 请在您的帖子中包含您的答案的相关代码/信息。仅一个链接是不够的,因为它可能会被破坏。
    • @Micho 按照建议,我从链接的博客中复制了示例(仅将 getInt(char) 方法更改为使用 switch-case)。
    • ... 并再次将其全部删除,因为问题范围已更改 :-)
    • 非常感谢!!抱歉,我的问题犯了一个错误,但这是一场下坡路!
    • @DylanBlack 很高兴它有帮助。顺便提一句。如果是,您可以接受答案。
    【解决方案2】:

    您必须创建基本值的索引并将其与数值匹配。 一个小例子:

    I = 1
    V = 5
    X = 10
    

    你必须看到左/右的位置才能相加和相减。 这是逻辑,代码由你决定。

    【讨论】:

      猜你喜欢
      • 2012-10-09
      • 1970-01-01
      • 2019-01-09
      • 2011-10-25
      • 1970-01-01
      • 2020-05-11
      • 2021-12-15
      相关资源
      最近更新 更多