It was the June 22th, 2004 when I posted this code on another blog. It was made to spend some time in the hot italian summer, not to be useful. However here it is
import java.io.IOException;
import java.util.HashMap;
/**
* Class that write a sentence in Morse Code
* @author
* @version 1.0.0
*
* Copyright (C) 2004
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Licence details at http://www.gnu.org/licenses/gpl.txt
*/
public class Morse {
private HashMap transcode = new HashMap();
public Morse(){
//initializing Transcode
transcode.put(”A”,”.-”);
transcode.put(”B”,”-…”);
transcode.put(”C”,”-.-.”);
transcode.put(”D”,”-..”);
transcode.put(”E”,”.”);
transcode.put(”F”,”..-.”);
transcode.put(”G”,”–.”);
transcode.put(”H”,”….”);
transcode.put(”I”,”..”);
transcode.put(”J”,”.—”);
transcode.put(”K”,”-.-”);
transcode.put(”L”,”.-..”);
transcode.put(”M”,”–”);
transcode.put(”N”,”-.”);
transcode.put(”O”,”—”);
transcode.put(”P”,”.–.”);
transcode.put(”Q”,”–.-”);
transcode.put(”R”,”.-.”);
transcode.put(”S”,”…”);
transcode.put(”T”,”-”);
transcode.put(”U”,”..-”);
transcode.put(”V”,”…-”);
transcode.put(”W”,”.–”);
transcode.put(”X”,”-..-”);
transcode.put(”Y”,”-.–”);
transcode.put(”Z”,”–..”);
transcode.put(”1″,”.—-”);
transcode.put(”2″,”..—”);
transcode.put(”3″,”…–”);
transcode.put(”4″,”….-”);
transcode.put(”5″,”…..”);
transcode.put(”6″,”-….”);
transcode.put(”7″,”–…”);
transcode.put(”8″,”—..”);
transcode.put(”9″,”—-.”);
transcode.put(”0″,”—–”);
}
/**
* Method that encode a message in morse code
* @param s: the clean message
* @return the message encoded
*/
public String encode(String s){
String ret = “”;
String elem = “”;
s = s.toUpperCase();
for(int i=0; i<s.length();i++){
elem = (String) transcode.get(String.valueOf(s.charAt(i)));
if(elem == null)
ret += String.valueOf(s.charAt(i));
else
ret += elem;
}
return ret;
}
public static void main(String[] args) {
Morse morse = new Morse();
String message = “”;
char lineSeparator = System.getProperty(”line.separator”,”n”).toCharArray()[0];
int in = 0;
System.out.print("Insert a phrase to encode (return to end) ");
try{
while((in = System.in.read()) != lineSeparator){
message += String.valueOf((char)in);
}
}catch(IOException ioe){
System.err.println(”error input the message”);
ioe.printStackTrace();
System.exit(1);
}
System.out.println(message + “= ” + morse.encode(message));
}
}