私は英語からモールス信号への翻訳者に取り組んでいます。英語で文章を入力すると、対応するモールス文字ではなく「null」で埋められた翻訳が表示されます。
結果は次のようになります: "null | null | null | null|null"。|
モールス文字の区切り文字です。nullを取り除くにはどうすればよいですか?これが私のコードです:
(はい、これは宿題です。)
import javax.swing.JOptionPane;
public class test
{
public static void main ( String [] args )
{
String s1 = "Morse";
//Decide whether Morse code or English
String decide = JOptionPane.showInputDialog("Enter 'English' for Morse to English code translation and 'Morse' for English to Morse code translation. Pay attention to Caps.");
//Enter String
String phrasep = JOptionPane.showInputDialog("Enter the words you wish to translate.");
if ( decide.equals( s1 ))
toMorse( phrasep );
else
toEnglish( phrasep );
}
// Translate to Morse
public static void toMorse( String phrase1 )
{
char[] english = new char[36];
for ( int i = 65, j = 0; i < 91; i++, j++) {
english[j] = (char)i;
}
english[26] = 1;
english[27] = 2;
english[28] = 3;
english[29] = 4;
english[30] = 5;
english[31] = 6;
english[32] = 7;
english[33] = 8;
english[34] = 9;
english[35] = 0;
String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..", ".---",
"-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-",
"...-",".--","-..-","-.--","--.."};
//Replace spaces with |
String phrase = phrase1.replace( "//s+", "|");
String[] translation = new String[phrase1.length()];
//Translate
for ( int j = 0, t = 0, n = 1; j < phrase.length(); j++) {
if ( phrase.substring(t, n ).equals ( english[j] ) ) {
translation[t] = morse[j];
t++;
n++;
}
}
String separatorp = new String( "|" );
arrayToString ( translation, separatorp );
}
public static void toEnglish( String phrase) {
System.out.println( phrase );
}
//Convert array to string and print translation
public static void arrayToString(String[] trans, String separator)
{
String result = "";
if (trans.length > 0) {
result = trans[0]; // start with the first element
for (int i = 1; i < trans.length; i++)
result = result + separator + trans[i];
}
System.out.println ( result );
}
}