mardi 3 mars 2015

Program for translating English to Morsecode JAVA [duplicate]




This question already has an answer here:




I am having trouble on a program that is supposed to translate English to morse code.



public class MorseCode
{
private static String [] english = { "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","1","2","3","4","5","6","7","8","9","0"};
private static ArrayList<String> morse = new ArrayList<String> ();
public MorseCode(String fileName) throws IOException
{
Scanner inFile = new Scanner(new File(fileName));
while(inFile.hasNext()){
morse.add(inFile.next());
}
}

public static void toMorse(String a)
{
String [] phrase = a.split("");
String translated = "";
for (String b : phrase)
{
for (int i = 0; i < 36; i++)
{
if (b == english[i])
{
translated += morse.get(i);
System.out.println(translated);
}

}


}

System.out.println(translated);
}


}


Basically, I have an array of english letters/numbers in the String array [] English. The Array List morse contains a list of morse characters that is read in from a file. The English Array and Morse Array List are the same length and correspond in terms of translation.


In the toMorse function, I have a String array phrase[] that has each individual letter of the user inputted message that is to be translated. For each letter in the message (each index in phrase[]), I go through each letter of the alphabet (english[]), and when I find a match, I take the same index of the match, and append the morse character of that index into a string.


I don't see any errors, but when I run the program there is just blank space after I type the message I want to be translated. I can't get the result to print out. I have made sure that most everything works, but I think there is something wrong in the for and if statements.


I have a separate class to run this:



public class MorseCodeTester
{
public static void main (String args[]) throws IOException
{
MorseCode m = new MorseCode ("morsecode.txt");
Scanner in = new Scanner (System.in);
System.out.println("Enter a message to translate to Morse Code: ");
String message = in.next();
message = message.toLowerCase();
m.toMorse(message);
}


}


Any help would be much appreciated. Thanks!




Aucun commentaire:

Enregistrer un commentaire