为什么不打印 space 之后的所有内容?

Why is everything after the space not printed?

我使用 acm 库创建了一个简单的程序,该程序接受用户输入的字符串并以莫尔斯码打印出来。这是程序:

import acm.program.*;

public class morse extends Program{
    public void run(){

        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"};
        String[] morse = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        String word = readLine("Give the word(s) to transcribe: ").toUpperCase();
        println("Morse: ");
        int j = 0;
        for(int i = 0; i < word.length(); i++){
            int k = 0;
            boolean flag = true;
            if(Character.toString(word.charAt(j)).equals(" ")){
                println();
            }else {
                while(!Character.toString(word.charAt(j)).equals(alphabet[k])){
                    if(k < 25){
                        k += 1;
                    }else{
                        println("Letter was not found.");
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    println(morse[k] + " ");
                }
            j += 1;
            }   
        }
    }
}

但是,每次字符串包含 space 时,都不会打印 space 之后的所有内容。我真的找不到这背后的原因。任何人都可以帮助我,甚至可以指出我的某个地方吗?谢谢

(space后面的字母都打印成spaces)

我不知道为什么你在 for 循环中定义了 i 但从未使用它。您的主要问题是,当您遇到 space 时,您不会增加 j。我想你有两个选择:

  • if
  • 中调用 println(); 后增加 j
  • 完全放弃 j 并在以前使用 j 的地方简单地使用 i(可能是更好的主意)

对您的代码的一般建议:您正在执行太多奇怪的字符和字符串逻辑。你可以做

  • 放下 alphabet
  • String 中获取 char 的方法与您当前的方法相同
  • 从中减去'A'
  • 使用结果 char 作为索引来访问 morse 数组
  • 删除 k 和整个 while 循环。