gpt4 book ai didi

java - 英语 - 莫尔斯翻译器

转载 作者:行者123 更新时间:2023-11-29 03:20:11 27 4
gpt4 key购买 nike

从摩尔斯语翻译成英语就像一个魅力,但是将一个短语或句子(多个单词用空格分隔)从英语翻译成摩尔斯语只会产生翻译成摩尔斯语的第一个单词。例如,如果我输入“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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com