为什么没有印刷空间后的所有东西?

时间:2018-01-04 15:05:30

标签: java acm

我使用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;
            }   
        }
    }
}

但是,每次字符串包含空格时,不会打印空格后的所有内容。我真的无法找到背后的原因。任何人都可以帮我,甚至指点我吗?感谢

(空格后的字母全部打印为空格)

1 个答案:

答案 0 :(得分:2)

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

    j 内拨打println();后,
  • 增加if
  • 完全删除j,只需使用i以前使用j的地方(可能是更好的主意)

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

  • 放弃alphabet
  • char获取String,与您目前的方式相同
  • 从中减去'A'
  • 使用生成的char作为索引来访问morse数组
  • 删除k和整个while循环。