I am creating a project that translate Morse Code into English and English into Morse Code. The program shall prompt the user to specify the desired type of translation, input a string of Morse Code characters or English characters, then display the translated results. All upper and lower case, numbers and punctuations could be ignored. And please do not use Hashtables and maps.
I manage to successfully finish writing the part to translate English to Morse. However, when translating Morse to English there seems to be a lot of errors going on. But I couldn't figure out why.
So anyone who's reading this, I would be so thankful if you help me solve the error! Any helps are appreciated. Thank you so much!
The error message that was displayed on the console was this :
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3 at java.lang.String.substring(String.java:1950) at Project1.MoToEng(Project1.java:57) at Project1.main(Project1.java:30)
public class Translator
{
public static String[] morse = { ".- ", "-... ", "-.-. ", "-.. ", ". ",
"..-. ", "--. ", ".... ", ".. ",
".--- ", "-.- ", ".-.. ", "-- ", "-. ", "--- ", ".--. ", "--.- ",
".-. ", "... ", "- ", "..- ",
"...- ", ".-- ", "-..- ", "-.-- ", "--.. ", "|" };
public static String[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
"v", "w", "x", "y", "z", " " };
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input '1' to translate English to Morse Code.");
System.out.println("Input '2' to translate Morse Code to English.");
int kind = in.nextInt();
if (kind == 1) {
System.out.println("Please insert an alphabet string");
String Eng = in.next();
EngToMo(Eng);
}
if (kind == 2) {
System.out.println("Please insert a morse string");
String Mor = in.next();
MoToEng(Mor);
}
}
public static void EngToMo(String string1) {
String Upper1 = string1.toUpperCase();
for (int i = 0; i < Upper1.length(); i++) {
char character1 = Upper1.charAt(i);
if (character1 != ' ') {
System.out.print(morse[character1 - 'A'] + " ");
} else {
System.out.println(" | ");
}
}
}
public static void MoToEng(String string2) {
int x = 0;
int y = 1;
String space = " ";
for (int i = 0; i < string2.length(); i++) {
if(string2.substring(x,y).equals(space)){
x++;
y++;
}
else{
y++;
if(string2.substring(x,y).equals(morse[i])){
System.out.println(alphabet[i]+ " ");
}
}
}
}
}