這個java代碼是將英文轉換成莫爾斯電碼。將英文轉換成MorseCode
當用戶輸入一個哨兵字符$時,該程序將終止。在輸入每個字符串後,程序將顯示其等價的莫爾斯碼,在字符和字之間留有空白(ø)。
EG。你好,世界。輸出應爲...ø.ø.- ..ø.- ..ø---ø.--ø---ø.-。ø.- ..ø-..
我的代碼有一些問題。 1.我不知道在用戶輸入ø時應該在哪裏放置$來終止程序; 2,輸出是正確的,但總是與結束(O),因爲System.out.print(code[variable] + "ø");
這裏是我的代碼:
public class Morse{
public static void main (String [] args)
{
Scanner englishtomorse = new Scanner(System.in);
System.out.println ("Please enter an original sentence in English.");
english = englishtomorse.nextLine();
String str = englishtoMorse(english);
System.out.println(str);
}
public static String englishtoMorse(String english)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String code[] = {"._", "_...", "_._.", "_..",".",".._.","__.", "....",
"..", ".___", "_._", "._..", "__","_ .", "___", ".__.", "__._", "._.",
"...", "_", ".._", "..._", ".__", "_.._", "_.__", "__.."};
english = english.toUpperCase();
for(int xyz = 0; xyz < english.length(); xyz++)
{
char letter = english.charAt(xyz);
if (letter == ' ')
{
System.out.print ("ø");
continue;
}
for(int variable = 0; variable < alphabet.length(); variable++)
{
if(alphabet.charAt(variable) == letter)
{
System.out.print(code[variable] + "ø");
break;
}
}
}
return " ";
}
您可能希望使用'-'而不是'_',以便您更輕鬆地識別破折號。 –
你可以用'System.out.print(代碼[letter - 'A'] +「ø」)替換你的''for'循環;'不編碼Java一段時間......你可能需要輸入字母 - '一個'int,不確定。 –