从莫尔斯翻译成英语就像一个魅力,但是将一个短语或句子(由空格分隔的多个单词)从英语翻译成莫尔斯只会产生翻译成莫尔斯语的第一个单词。例如,如果我要输入“Hello World'”,翻译人员只会返回
' .... .- .. ..- .. ---'。
为了从翻译中获得完整的句子,我需要更改什么?我已经指出了我认为问题所在,并注意到翻译忽略了标点符号。 TIA
import java.util.Scanner;
public class JavaProgram
{
//made them static so they can be accessed from static functions
private final static char[] ABC = {'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', ' '};
private final static String[] MORSE = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-" ,".--" ,"-..-", "-.--", "--..", "|"};
public static void main(String [] args)
{
Scanner scan = new Scanner( System.in );
System.out.print("If you want to convert from Morse to English, type 'M', if you would like to convert from English to Morse, type 'E': ");
String answer = scan.nextLine();
if( answer.equals("E"))
{
Scanner scan2 = new Scanner(System.in);
System.out.print("Enter a word or phrase in English: ");
String englishInput = scan.next();
System.out.println(toMorse(englishInput));
scan2.close();
}
if (answer.equals("M"))
{
Scanner scan3 = new Scanner(System.in);
System.out.print("Enter a word or phrase in Morse: ");
String morseInput = scan.nextLine();
System.out.println(getABC(morseInput));
scan3.close();
}
scan.close();
}
private static String toMorse(String ABCString)
{
String morseString = "";
for (char c : ABCString.toLowerCase().toCharArray())
{
morseString += charToMorse(c) + " ";
}
return morseString;
}
//**I am fairly certain the problem is in this method.**
private static String charToMorse(char c)
{
for(int i = 0; i < ABC.length; ++i)
{
if (c == ABC[i])
{
return MORSE[i];
}
}
return String.valueOf(c);
}
private static String getABC(String morseString)
{
String ABCString = "";
for (String s : morseString.split("\\s"))
{
ABCString += characterToABC(s);
}
return ABCString;
}
private static String characterToABC(String s)
{
for (int i = 0; i < MORSE.length; ++i)
{
if (s.equals(MORSE[i]))
{
return String.valueOf(ABC[i]);
}
}
return s;
}
}
答案 0 :(得分:4)
我相信,基于http://www.tutorialspoint.com/java/util/scanner_next.htm(java.util.Scanner.next的定义),您在本节中的String englishInput = scan.next();
行:
if( answer.equals("E"))
{
Scanner scan2 = new Scanner(System.in);
System.out.print("Enter a word or phrase in English: ");
String englishInput = scan.next();
System.out.println(toMorse(englishInput));
scan2.close();
}
只读取第一个标记,这是第一个单词,因为单个空格是空格,而不是正确接受整个句子的nextLine()。