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

Java实现字母转摩尔斯电码 如何通过双数组索引对应完成匹配

核心实现思路

你定义的tLettre和tMorse两个数组长度相同,相同下标位置的元素天然是一一对应的,只要遍历字母数组找到用户输入字母的下标,取摩尔斯数组同下标的值即可。


需要补充到main方法末尾的代码

// 统一转为大写,兼容小写输入
char lettreUpper = Character.toUpperCase(lettre);
String resultat = null;

// 遍历字母数组匹配输入
for (int i = 0; i < tLettre.length; i++) {
    if (tLettre[i] == lettreUpper) {
        resultat = tMorse[i];
        // 匹配到直接终止循环,无需继续遍历
        break;
    }
}

// 输出结果
if (resultat != null) {
    JOptionPane.showMessageDialog(null, "Traduction Morse : " + resultat);
} else {
    JOptionPane.showMessageDialog(null, "Erreur : veuillez saisir une lettre valide (A-Z)");
}

完整可运行代码

import javax.swing.JOptionPane;

/**
 *
 * @author alex_
 */
public class Morse {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        char lettre = ' ';
        
        char tLettre[] = {'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'};
        String tMorse[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",
               ".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-",
               "..-","...-",".--","-..-","-.--","--.."};
        
        lettre = JOptionPane.showInputDialog("Entrez la lettre que vous voulez traduire: ").charAt(0);
        
        // 新增逻辑开始
        char lettreUpper = Character.toUpperCase(lettre);
        String resultat = null;

        for (int i = 0; i < tLettre.length; i++) {
            if (tLettre[i] == lettreUpper) {
                resultat = tMorse[i];
                break;
            }
        }

        if (resultat != null) {
            JOptionPane.showMessageDialog(null, "Traduction Morse : " + resultat);
        } else {
            JOptionPane.showMessageDialog(null, "Erreur : veuillez saisir une lettre valide (A-Z)");
        }
        // 新增逻辑结束
    }
    
}

关键说明

  • 新增Character.toUpperCase处理是为了兼容用户输入小写字母的场景,避免输入小写a时匹配不到大写A的问题
  • 遍历数组时只要匹配到目标字母就用break终止循环,减少不必要的遍历操作
  • 新增了非法输入的提示逻辑,当用户输入非英文字符时会给出错误提示

内容的提问来源于stack exchange,提问作者Alex d'Astous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:06:09