我的导师给了我一个挑战,让用户输入一个数字或罗马数字并让程序将其转换为另一个。我已经能够将整数转换为罗马数字,但我不知道如何以相反的方式进行。我曾尝试寻求帮助,但对我的情况没有任何帮助。你们中的一些人可能给了我链接或说这是重复的,但是,我知道如何进行转换(是的,我在这个问题上犯了 巨大 错误)。我的问题是能够同时做到这两点。我不知道如何让它像:哦,你输入一个整数,将其转换为罗马数字,并且它也像:哦,罗马数字时间!将其转换为整数。 请帮助!!
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]");
}
}
答案 0 :(得分:1)
根据您的上一次编辑,要识别您获得的输入类型,您可以使用Scanner.hasNextInt()方法:
param_date
答案 1 :(得分:1)
您必须创建基本值的索引并将其与数值匹配。 一个小例子:
I = 1
V = 5
X = 10
你必须看左/右位置求和和减去。 这是逻辑,代码取决于你。