Ak Java Freak
Posts : 23 Join date : 2009-02-07
| Subject: java convert binary to roman numeral Mon Apr 27, 2009 8:20 am | |
| main class - Code:
-
import java.io.*; public class roman { public static void main(String args[])throws IOException { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String StrRoman; int mynumber;
System.out.println("Enter a number to convert: "); mynumber = Integer.parseInt(reader.readLine());
StrRoman = RomanNumeralConverter.BinaryToRoman(mynumber); // call the class RomanNumeralConverter and Method BinaryToRoman System.out.println(StrRoman); // print output to screen with string variable because roman numerals are string }// end try catch(NumberFormatException ex) { System.out.println("Error"); }// end catch }// end main method }// end roman class
RomanNumeralConverter class - Code:
-
public class RomanNumeralConverter { private static String Roman_Numeral[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; private static int number[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
public static String BinaryToRoman(int binary) { if (binary <= 0 || binary >= 4000) { throw new NumberFormatException("Out of range!"); }// end if statement
String roman = "";
for(int index = 0; index < Roman_Numeral.length; index++) { while(binary >= number[index]) { binary-=number[index]; roman += Roman_Numeral[index]; } } return roman; } // end BinaryToRoman method }// end RomanNumeralConverter class
| |
|