作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
从摩尔斯语翻译成英语就像一个魅力,但是将一个短语或句子(多个单词用空格分隔)从英语翻译成摩尔斯语只会产生翻译成摩尔斯语的第一个单词。例如,如果我输入“Hello World”,翻译器只会返回
'…… .-. .-.. --- '.
为了从翻译者那里获得完整的句子,我需要更改什么?我已经指出了我认为的问题所在,并注意译者忽略了标点符号。时间差
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;
}
}
最佳答案
我相信,基于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() 正确接受整个句子。
关于java - 英语 - 莫尔斯翻译器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24153406/
我是一名优秀的程序员,十分优秀!