Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner; // for user input
- public class Decimal2Roman {
- /**
- * Program: Decimal2Roman.java
- * Purpose: Convert decimal number to Roman numerals
- * Creator: Chris Clarke
- * Created: 05.11.2012
- */
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- int decimal = 0;
- if (args.length > 0) {
- try {
- decimal = Integer.parseInt(args[0]);
- } catch (Exception e) {
- System.out.println("Not a whole number!");
- System.exit(1);
- } // end try/catch
- } else {
- System.out.print("Enter a whole number"
- +" for conversion to Roman: ");
- try {
- decimal = scan.nextInt();
- } catch (Exception e) {
- System.out.println("That\'s not a whole number!");
- System.exit(1);
- } // end try/catch
- } // end if/else
- System.out.println("In Roman numerals: "
- + getRomanNumerals( decimal));
- } // end main()
- public static String getRomanNumerals(int decimal) {
- String ans="";
- if (decimal<0) {
- System.out.println("Postive numbers only!");
- return "Error";
- } else if (decimal>=4000) {
- System.out.println("Number too big"
- +" - must be less than 4000");
- return "Error";
- } // end if/else
- while (decimal>=1000) {
- ans += "M";
- decimal -= 1000;
- } // end while
- if (decimal>=900) {
- ans += "CM";
- decimal -= 900;
- } else if (decimal>=500) {
- ans += "D";
- decimal -= 500;
- } else if (decimal>=400) {
- ans += "CD";
- decimal -= 400;
- } // end if/else
- while (decimal>=100) {
- ans += "C";
- decimal -= 100;
- } // end while
- if (decimal>=90) {
- ans += "XC";
- decimal -= 90;
- } else if (decimal>=50) {
- ans += "L";
- decimal -= 50;
- } else if (decimal>=40) {
- ans += "XL";
- decimal -= 40;
- } // end if/else
- while (decimal>=10) {
- ans += "X";
- decimal -= 10;
- } // end while
- if (decimal==9) {
- ans += "IX";
- decimal -= 9;
- } else if (decimal>=5) {
- ans += "V";
- decimal -= 5;
- } else if (decimal==4) {
- ans += "IV";
- decimal -= 4;
- } // end if/else
- while (decimal>=1) {
- ans += "I";
- decimal--;
- } // end while
- return ans;
- } // end getRomanNumerals()
- } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement