我正在尝试编写一个需要用户输入并将其转换为莫尔斯电码的应用程序
功能代码:
public static String[] stringToMorseSequence(String stringOfLetters){
int lenStringOfLetters = stringOfLetters.length();
String output[] = new String[1];
String compInterpreted = "";
for(int i = 0; i < lenStringOfLetters; i++) {
String focus = String.valueOf(stringOfLetters.charAt(i));
String nextCharacter = "";
if (i != lenStringOfLetters) {
nextCharacter = String.valueOf(stringOfLetters.charAt(i + 1));
} else {
nextCharacter = "END";
}
if (focus == " ") {
compInterpreted = compInterpreted + "#";
} else {
String morseSequence = processCharacter(focus);
if (morseSequence == "") {
} else if (i == lenStringOfLetters) {
compInterpreted = compInterpreted + "!";
} else if (nextCharacter != "END") {
if (nextCharacter != " "){
compInterpreted = compInterpreted + morseSequence + "@";
} else {
compInterpreted = compInterpreted + morseSequence;
}
}
}
}
Log.i("MORSE","Computer interpretable morse sequence = " + compInterpreted);
output[0] = compInterpreted;
String prettySequence = "";
for(int i = 0; i-1 < output[0].length(); i++) {
switch(String.valueOf(output[0].charAt(i))){
case("#"):
prettySequence = prettySequence + " ";
case("@"):
prettySequence = prettySequence + " ";
default:
prettySequence = prettySequence + output[0].charAt(i);
}
}
Log.i("MORSE","Human interpretable morse sequence = " + prettySequence);
output[1] = prettySequence;
return output;
}
我似乎正在收到此异常
E/AndroidRuntime: FATAL EXCEPTION: main
Process: me.merhlim.jessica.morsecode, PID: 5687
java.lang.StringIndexOutOfBoundsException: length=10; index=10
at java.lang.String.charAt(Native Method)
at me.merhlim.jessica.morsecode.MorseProcessing.stringToMorseSequence(MorseProcessing.java:16)
at me.merhlim.jessica.morsecode.texttomorse$7.onClick(texttomorse.java:112)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:108)
我知道这是一个逻辑错误,但是我不确定该错误在哪里或如何解决。如错误消息所述,当尝试解析字符串中的特定字符时,它是一个索引错误,但是我不确定该错误被抵消的逻辑是什么
我是java的新手,并且它很晚,所以也许我只是没有完全理解我正在编写的逻辑中的问题
如果这些信息不足以回答我的问题,我可以提供更多
感谢您抽出宝贵的时间阅读本文档,如果您提供帮助,我们将不胜感激 -杰西卡
答案 0 :(得分:2)
当我在9点(小于长度10)时,调用
$
将尝试使角色位于第10位。但是,字符串的长度只有10,最后一个字符位于位置9,这导致字符串索引超出范围。您可能要更改此
nextCharacter = String.valueOf(stringOfLetters.charAt(i + 1));
到
if (i != lenStringOfLetters) {