我的導師給了我一個挑戰,讓用戶輸入一個數字或羅馬數字並讓程序將其轉換爲另一個數字。我已經使它能夠將一個整數轉換爲羅馬數字,但我不知道如何以相反的方式進行操作。我試過尋求幫助,但對我的情況沒有任何幫助。有些人可能已經給我鏈接或說這是重複的,但是,我知道如何做轉換(是的,我提出了一個巨大的與此問題的錯誤)。我的問題是能夠同時做到這一點。我不知道如何讓它像:哦,你輸入一個整數,將它轉換爲羅馬數字,並且它也是這樣的:哦,羅馬數字時間!將其轉換爲整數。 請幫助!將羅馬數字轉換爲Java中的整數
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]");
}
}
請在您的帖子中包含您的答案的相關代碼/信息。只有一個環節是不夠的,因爲它可以被打破。 – Micho
@Micho建議,我從鏈接的博客複製了示例(只更改了getInt(char)方法以使用switch-case)。 – Carsten
...並將其全部刪除,因爲問題範圍發生了變化:-) – Carsten