我使用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;
}
}
}
}
但是,每次字符串包含空格时,不会打印空格后的所有内容。我真的无法找到背后的原因。任何人都可以帮我,甚至指点我吗?感谢
(空格后的字母全部打印为空格)
答案 0 :(得分:2)
我不知道为什么你在i
循环中定义for
但从不使用它。您的主要问题是,当您遇到空格时,您不会增加j
。我认为你有两个选择:
j
内拨打println();
后,if
j
,只需使用i
以前使用j
的地方(可能是更好的主意)您的代码的一般建议:您正在执行太多奇怪的字符和字符串逻辑。你可以做到
alphabet
char
获取String
,与您目前的方式相同'A'
char
作为索引来访问morse
数组k
和整个while
循环。