You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java摩尔斯电码转换程序输入阶段卡顿问题求助

英文转摩尔斯电码程序输入阻塞问题及修复

我写了一个用字符串方法实现英文到摩尔斯电码转换的程序,但执行时会在int KeyIndex = 0;这一行之前卡住,一直停在输入模式。目前只做了英文转摩尔斯的循环逻辑,还没写反向转换的代码。

原代码如下:

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

  char[] EngMorseArray =
  { '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' };

  String[] MorseEngArray =
  { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
        "--.-", ".-.", "…", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--",
        "....-", ".....", "-....", "--...", "---..", "----." };

  // First we identify if we are going eng - morse or vice versa
  System.out.println("for Eng -> Morse, enter 1.  for Morse -> Eng, enter 2");
  String WhichConversion = input.next();

  if (WhichConversion.equals("1")) // English to Morse
  {
     System.out.println("What is the text you would like coded?"
           + " (lowercase a-z and 0-9 with a space between words, " + "please) ");
     
     String CharString = input.nextLine(); // this line is here twice
     CharString = input.nextLine(); // to avoid nextInt/nextLine issue
     
     char[] CharStringArray = new char[CharString.length() + 1];
     
     
     for (int index = 0; index < CharString.length(); index++) // Convert string to char array
     {
        CharStringArray[index] = CharString.charAt(index);
        System.out.print(CharStringArray[index]);
     }
     /*
      * convert from char Array to string again for (int index = 0; index <=
      * CharStringArray[index]; index++) { String charString = ""; charString +=
      * CharStringArray[index]; }
      */
     
     int KeyIndex = 0;
     int InputIndex;

     for (InputIndex = 0; InputIndex < EngMorseArray.length; InputIndex++)
     {

        while (KeyIndex <= EngMorseArray.length)
        {
           
           if (EngMorseArray[KeyIndex] == CharStringArray[InputIndex])
           {
              System.out.println(MorseEngArray[KeyIndex] + " ");
              KeyIndex++;
           } else if (CharStringArray[InputIndex] == ' ')
           {
              System.out.println(" | ");
              KeyIndex++;
           }

问题分析

  • 输入处理逻辑混乱:使用input.next()获取转换选择后,输入缓冲区残留的换行符会被第一个input.nextLine()读取,导致程序需要等待第二次输入,看起来像是卡住。
  • 循环逻辑错误:外层for循环遍历的是字符映射数组EngMorseArray的长度,而非用户输入的字符数量;内层while循环的终止条件KeyIndex <= EngMorseArray.length会触发数组越界(数组下标最大值为长度-1)。
  • 冗余字符数组:将输入字符串转成额外的字符数组完全没必要,徒增复杂度。

修复后的代码

import java.util.Scanner;

public class MorseConverter {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        char[] engMorseArray =
                {'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'};

        String[] morseEngArray =
                {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
                        "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--",
                        "....-", ".....", "-....", "--...", "---..", "----."};

        // 选择转换方向
        System.out.println("英文转摩尔斯请输入1,摩尔斯转英文请输入2");
        String whichConversion = input.next();
        // 清除输入缓冲区的换行符
        input.nextLine();

        if (whichConversion.equals("1")) { // 英文转摩尔斯
            System.out.println("请输入要编码的文本(仅限小写a-z、0-9,单词间用空格分隔):");
            String inputText = input.nextLine();

            // 遍历输入的每个字符
            for (int i = 0; i < inputText.length(); i++) {
                char currentChar = inputText.charAt(i);
                if (currentChar == ' ') {
                    // 空格表示单词分隔,输出|
                    System.out.print(" | ");
                    continue;
                }
                // 查找匹配的摩尔斯码
                boolean matched = false;
                for (int j = 0; j < engMorseArray.length; j++) {
                    if (engMorseArray[j] == currentChar) {
                        System.out.print(morseEngArray[j] + " ");
                        matched = true;
                        break;
                    }
                }
                // 未匹配到的字符输出?
                if (!matched) {
                    System.out.print("? ");
                }
            }
        }
        // 可在此补充摩尔斯转英文的逻辑
        input.close();
    }
}

修复说明

  • 修正输入处理:在input.next()后调用input.nextLine()清除缓冲区的换行符,避免多余的输入等待。
  • 重构循环逻辑:外层循环遍历用户输入的每个字符,内层循环遍历映射数组查找匹配项,找到后立即跳出循环,提升效率。
  • 移除冗余代码:直接使用charAt()获取输入字符,不需要额外的字符数组。
  • 增加健壮性:对未匹配的字符输出?,避免程序无响应。

内容的提问来源于stack exchange,提问作者Puppy_With_Pinecone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:44:52