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

如何将Java摩尔斯码转换程序的输出打印在同一行?

解决Java摩尔斯码转换程序输出换行问题

你的问题出在使用了System.out.println()——这个方法每次执行都会自动换行,和你加的toString()完全没关系(substring(1)返回的本身就是字符串,调用toString()是多余操作)。

最简单的解决办法就是把println换成print,如果需要字符间用空格分隔,还可以在输出内容后加空格:

public class morse { 
    public static void main(String[] args) { 
        String word = "word"; 
        String[] alphabet = {"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--.."}; 
        for (int i = 0; i < word.length() ; i++) { 
            for (int j = 0; j < alphabet.length; j++) { 
                if (alphabet[j].charAt(0) == word.charAt(i)) { 
                    // 替换println为print,添加空格分隔摩尔斯码
                    System.out.print(alphabet[j].substring(1) + " "); 
                } 
            } 
        }
        // 最后换行让输出更整洁
        System.out.println();
    } 
}

如果想让代码更高效(避免嵌套循环遍历数组),可以用HashMap存储字符与摩尔斯码的映射,直接通过字符取值:

import java.util.HashMap;
import java.util.Map;

public class MorseConverter {
    public static void main(String[] args) {
        String word = "word";
        Map<Character, String> morseMap = new HashMap<>();
        morseMap.put('a', ".-");
        morseMap.put('b', "-...");
        morseMap.put('c', "-.-.");
        morseMap.put('d', "-..");
        morseMap.put('e', ".");
        morseMap.put('f', "..-.");
        morseMap.put('g', "--.");
        morseMap.put('h', "....");
        morseMap.put('i', "..");
        morseMap.put('j', ".---");
        morseMap.put('k', "-.-");
        morseMap.put('l', ".-..");
        morseMap.put('m', "--");
        morseMap.put('n', "-.");
        morseMap.put('o', "---");
        morseMap.put('p', ".--.");
        morseMap.put('q', "--.-");
        morseMap.put('r', ".-.");
        morseMap.put('s', "...");
        morseMap.put('t', "-");
        morseMap.put('u', "..-");
        morseMap.put('v', "...-");
        morseMap.put('w', ".--");
        morseMap.put('x', "-..-");
        morseMap.put('y', "-.--");
        morseMap.put('z', "--..");

        StringBuilder result = new StringBuilder();
        for (char c : word.toCharArray()) {
            result.append(morseMap.get(c)).append(" ");
        }
        System.out.println(result.toString().trim());
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:00:42