我正在研究英语到莫尔斯语的翻译器。当我用英语输入我的句子时,我收到一个充满“空”而不是相应的莫尔斯字符的翻译。
结果如下所示:“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 );
}
}