我的代码有问题。我被要求使用包含莫尔斯电码和类似值的 txt 创建一个并行数组。例如:A .- 乙-... 等等...
这是我的错误所在-
public class Translate
{
String input;
String code[];
String alphabet[];
public Translate(String input)
{
this.input = input;
}
public void setInput(String input)
{
this.input = input;
}
public void setAlph(String[] alphabet)
{
this.alphabet = alphabet;
}
public void setCode(String[] code)
{
this.code = code;
}
public String getInput()
{
return input;
}
public String getTranslate()
{
String output = "";
for(int i = 0; i < input.length(); i++)
{
for(int index = 0; index < alphabet.length; index++)
{
if(input.charAt(i) == alphabet[index].charAt(0)
{
output = output + code[index];
}
}
}
return output;
}
}
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:36
我通常不会寻求帮助,但我已经在这方面花了几个小时了。 我能看到将 input.charAt 与字母表(字符串)进行比较的唯一方法是将字符串解析为 char 或在末尾添加 .charAt 。我尝试过 Alphabet[index].charAt(index)) 但这也不起作用。它给了我同样的错误,只有 1 而不是 36
UPD 我收到错误“Translate.getTranslate(Translate.java:39) 处的线程“main”java.lang.NullPointerException 异常”
UPD 不再接收错误。然而,我对下一个任务感到困惑。我需要在更多代码字母之间添加 1 个空格,在单词之间添加 3 个空格。 例如:如果“Hey”是用户输入,则与我收到的“.....-.--”相比,输出应该是“.... . -.--”
提前致谢。
最佳答案
看来您的问题是for(int index = 0; index <= alphabet.length; index++)
- 你不断增加index
直到它等于字母表的长度,这将使其超过末尾,给出您所得到的异常。你应该做到index < alphabet.length
以避免这种情况。
关于java - java 数组输出中的间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15961386/