0

嗨,我正在尝试制作一个将英语翻译成莫尔斯语的 java 程序,反之亦然。基本上我很难让所有东西变得兼容..以及如何使用replace all方法来让所有输入的变量被对应的i Morse索引替换。我并不想走这么多捷径……我真的很努力,想完成这件事。太感谢了!

    import java.util.Scanner;

       public class ProjMorse
     {
    public static void main( String [] args )
    {
       Scanner input = new Scanner(System.in);
      String [] alpha =  {"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","1","2","3","4","5","6","7","8","9","0"," "};
    String [] dottie = {".-", "-...", "-.-.", "-..", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----", "|"};
    System.out.println("To convert from English to Morse enter English");
String ans = input.nextLine();
    if(ans.equals("English"))
    {
  System.out.println( "Please enter the text you would like to convert to Morse Code: ");
      String English = input.nextLine();
  char[] translates = (English.toLowerCase()).toCharArray();

  for (int i = 0; i < alpha.length; i++)
  {
        String s  = translates[i].replaceAll('i', (dottie[i]));
  }
  String s = new String(dottie[i]);
      System.out.println(s);
    }
    else
    {
  System.out.println( "Please enter the text you would like to convert to English (separate words with '|'):");
  String code = input.nextLine();
  String[] translates = code.split("[|]", 0);

  for (int j = 0; j < dottie.length; j++)
  {
    alpha[j] = String.valueOf(translates[j]);
  }
  String s = new String(alpha[j]);
  System.out.println(s);
}
    }
  }
4

1 回答 1

1
  for (int i = 0; i < alpha.length; i++)
  {
        String s  = translates[i].replaceAll('i', (dottie[i]));
  }

这行不通,您要做的是逐步遍历要翻译的字符串的每个字符(您已将其转换为 char 数组),并replaceAll使用摩尔斯电码字母表中的相对索引执行字母“i”的实例. replaceAll是 String 类的一个方法,这是行不通的。

如果您尚未将其转换为 char 数组,则可以对包含 in 中的每个项目replaceAll的明文字符串执行 a 。 alphadottie

 int characterIndex = 0;
 for (char c : alpha)
 {
   plaintextString.replaceAll(c, dottie[characterIndex]);
   characterIndex++;
 }

此外...

首先,如果您要问一个问题,它应该包含一个问题,带有问号和所有内容。这样我们就知道我们在回答什么。如果你有一个错误,你需要包括那是什么错误。您还需要更好地格式化您的代码,这真的很难阅读......

现在,请注意您的代码,不要尝试用一种方法做所有事情,这很难看,很难阅读和调试。方法应该做一件事(而不是多件事,比如获取用户输入、翻译、输出)并做好。这背后的原因是,如果您可以在一个屏幕上阅读整个内容,则可以更好更快地理解方法的目的。

此外,变量应以小写字母开头,因此可能会造成混淆:-

String English = input.nextLine();
于 2014-01-01T19:07:32.407 回答