package testate; import java.applet.*; import java.awt.*; import java.awt.event.*; public class RomanArabicApp extends Applet { private Label headline; private TextField textField1; private TextField textField2; public void init () { headline = new Label (); textField1 = new TextField (); textField2 = new TextField (); setLayout (new BorderLayout ()); setBackground (Color.white); resize(350, 100); headline.setText ("Konvertierung Arabischer und Römischer Zahlen:"); add (headline, BorderLayout.NORTH); textField1.setText ("3999"); textField1.addTextListener (new TextListener () { public void textValueChanged (TextEvent evt) { textField1TextValueChanged (evt); } } ); add (textField1, BorderLayout.CENTER); textField2.setEditable (false); textField2.setText ("Bitte geben Sie oben einen Wert ein."); add (textField2, BorderLayout.SOUTH); } public void textField1TextValueChanged (TextEvent evt) { String text=textField1.getText(); String ausgabe=""; int zahl=0; boolean istZahl=false; if (text.compareTo("")!=0) { try { Integer temp=Integer.valueOf(text); zahl=temp.intValue(); istZahl=true; } catch (NumberFormatException e) {} if (istZahl) { ausgabe=ausgabe+RomanArabic.toRoman(zahl); } else { if (RomanArabic.toArabic(text)<0) { ausgabe="Sie haben keine römische Zahl eingegeben!"; } else { ausgabe=ausgabe+RomanArabic.toArabic(text); } } textField2.setText(ausgabe); } } } class RomanArabic extends Object { public RomanArabic() { } public static int toArabic(String roman) { int arabic=0; char temp; int index; boolean V=false, L=false, D=false; int laenge=roman.length(); int[] array=new int[laenge]; roman=roman.toUpperCase(); for (index=0; index=1)&&(array[index-1]<=array[index])) return -1; } else arabic=arabic+array[index]; } return arabic+array[laenge-1]; } public static String toRoman(int zahl){ String roman=""; int arabic=zahl; //Definitionsbereich: if ((arabic>0)&&(arabic<4000)) { //Greedy-Algorithmus: while (zahl>=1000) { zahl-=1000; roman=roman+"M"; } while (zahl>=900) { zahl-=900; roman=roman+"CM"; } while (zahl>=500) { zahl-=500; roman=roman+"D"; } while (zahl>=400) { zahl-=400; roman=roman+"CD"; } while (zahl>=100) { zahl-=100; roman=roman+"C"; } while (zahl>=90) { zahl-=90; roman=roman+"XC"; } while (zahl>=50) { zahl-=50; roman=roman+"L"; } while (zahl>=40) { zahl-=40; roman=roman+"XL"; } while (zahl>=10) { zahl-=10; roman=roman+"X"; } while (zahl>=9) { zahl-=9; roman=roman+"IX"; } while (zahl>=5) { zahl-=5; roman=roman+"V"; } while (zahl>=4) { zahl-=4; roman=roman+"IV"; } while (zahl>=1) { zahl-=1; roman=roman+"I"; } } else { roman="Ausserhalb des Definitionsbereiches!"; } return roman; } public static void main(String[] args) { for (int index=0; index<=100; index++) { System.out.println(index+" = "+toRoman(index)+" = "+toArabic(toRoman(index))); } System.out.println("MIMCIM = "+toArabic("MIMCIM")); } }