此代码在三倍空格之后重复输出。我只想在单词后面加上三倍空格,但输出会不断重复。例如,我只想查看输出:.-(三倍空格).-;
String english = input.nextLine();
char[] toChar = english.toCharArray();
String output = "";
for (int i = 0; i < toChar.length; i++) {
if (toChar[i] == 'a' || toChar[i] == 'A') {
output += ".-";
}
if (toChar[i] == 'b' || toChar[i] == 'B') {
output += "-...";
}
if (toChar[i] == ' ') {
output += " ";
}
System.out.print(output + " ");
}
输入值
a a
输出量
.- .- .- .-
最佳答案
您的帖子太混乱了。尝试对以后的帖子更加清楚。但是,由于输出在循环内(对输入数据的每个字符重复),因此将重复输出。因此,将您的System.out(....);
外循环。
String english = input.nextLine();
char[] toChar = english.toCharArray();
String output = "";
for (int i = 0; i < toChar.length; i++) {
if (toChar[i] == 'a' || toChar[i] == 'A') {
output += ".-";
}
if (toChar[i] == 'b' || toChar[i] == 'B') {
output += "-...";
}
if (toChar[i] == ' ') {
output += " ";
}
}
System.out.print(output + " ");