Napisałem dwie proste klasy do konwersji liczb z rzymskich na arabskie i odwrotnie. I z obydwiema mam problemy:
1) Kompilator nie wyrzuca błędu, ale środowisko się zawiesza, komp zaczyna szybciej pracować, ale rezultatów nie ma
package pl.example.Converter;
/**
*
* @author Mateusz Koza
*/
public class ArabaToRoma {
private int[] Araba1 = {1000, 500, 100, 50,10,5,1};
private int[] Araba2 = {900,400,90,40,9,4};
private String[] Roma1 = {"M", "D", "C", "L", "X", "V", "I"};
private String[] Roma2 = {"C", "C", "X", "X", "I", "I"};
public ArabaToRoma() {}
public String convertToRoma(int Araba) {
int Tempoary = Araba;
String Result = "";
while(Tempoary > 0) {
int i = 0;
if(Tempoary >= Araba1[i]) {
Tempoary -= Araba1[i];
Result = Result + Roma1[i];
if(Tempoary >= Araba2[i]) {
Tempoary -= Araba2[i];
Result = Result + Roma2[i];
Result = Result + Roma1[i];
}
else {
i++;
}
}
}
return Result;
}
}
2) W drugą stronę wyrzuca błędy:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(Unknown Source)
package pl.example.Converter;
/**
*
* @author Mateusz Koza - 3D7 - 171957
*/
public class RomaToAraba {
private int[] Araba1 = {1000, 500, 100, 50,10,5,1};
private int[] Araba2 = {900,400,90,40,9,4};
private char[] Roma1 = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
private char[] Roma2 = {'C', 'C', 'X', 'X', 'I', 'I'};
public RomaToAraba() {}
public int convertToAraba(String Roma) {
int Result = 0;
for(int i = 0; i < Roma.length(); i++) {
for(int j = 0; j < 7; i++) {
if(Roma.charAt(i)==(Roma2[j]) && Roma.charAt(i+1)==Roma1[j]) {
Result += Araba2[j];
i++;
}
else {
if(Roma.charAt(i) == Roma1[j]) {
Result += Araba1[j];
}
}
}
}
return Result;
}
}