Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。












想改善这个问题吗?更新问题,以使为on-topic

6年前关闭。



Improve this question





嗨,我正在尝试制作一个将英语翻译为莫尔斯语,反之亦然的Java程序。
基本上,我很难使所有内容都变得兼容..以及如何使用全部替换方法来获取输入的所有变量,并用对应于莫尔斯索引的变量替换。我并没有尝试太多的捷径..我真的很努力,希望做到这一点。非常感谢!

    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);
}
    }
  }

最佳答案

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


这将行不通,您要做的是逐步浏览要转换的字符串的每个字符(已转换为char数组),并在字母'i'的replaceAll实例中使用相对索引莫尔斯电码字母。 replaceAll是String类的方法,此方法不起作用。

如果尚未将其转换为char数组,则可以对包含replaceAll中每个字符的纯文本字符串中的alpha进行dottie

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


另外...

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

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

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

String English = input.nextLine();

10-08 04:11