gpt4 book ai didi

java - 为什么空格后面的所有内容都不打印?

转载 作者:行者123 更新时间:2023-12-02 02:23:39 28 4
gpt4 key购买 nike

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

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

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

最佳答案

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

  • if 内调用 println(); 后递增 j
  • 完全删除j,只需在以前使用过j的地方使用i(可能是更好的主意)
<小时/>

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

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

关于java - 为什么空格后面的所有内容都不打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48098057/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com