【发布时间】:2015-04-09 12:50:16
【问题描述】:
此方法所属的程序使用简单密码(即“ABCD”到“1,2,3,4”或“1,2,3,4”到“ABCD”)对消息进行编码和解码。编码消息包含的数字以冒号分隔。字符串中的每个值都应该转换为整数,然后转换为字符,最后连接成结果字符串。这种方法应该递归解码消息,但这是我第一次搞乱递归,所以它还没有功能。这是我收到的错误
“线程“AWT-EventQueue-0”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1”。
方法:
public static String DecodeR(String msg, String result) {
if (msg.length()>0) {
int pos =1;
pos += msg.indexOf(",");
int x = Integer.parseInt(msg.substring(0,msg.indexOf(",")));
if (x==0) {
x=32;
return DecodeR ((msg.substring(msg.indexOf(pos))),result+=String.valueOf((char)x));
} else if (x==99) {
x=63;
return DecodeR ((msg.substring(msg.indexOf(pos))),result+=String.valueOf((char)x));
} else {
x=x+64;
return DecodeR ((msg.substring(msg.indexOf(pos))),result+=String.valueOf((char)x));
}
} else {
return result;
}
}//end of DecodeR
编辑:我未能正确设置导致递归继续的基本情况,直到它导致负索引位置。此外,我对 substring 和 indexOf 的理解也很缺乏,首先导致字符串解析不正确。完成代码:
public static String DecodeR(String msg, String result) {
if (msg.length() == 0) {
return result;
}
int commaPosition = msg.contains(",") ? msg.indexOf(",") : msg.length();
int charCode = Integer.parseInt(msg.substring(0, commaPosition));
String remainingString = msg.contains(",") ? msg.substring(commaPosition+1, msg.length()) : "";
if (charCode == 0) {
charCode = 32;
} else if (charCode == 99) {
charCode = 63;
} else {
charCode += 64;
}
result += String.valueOf((char)charCode);
return DecodeR(remainingString, result);
}//end of DecodeR
感谢您的帮助,非常感谢您的建议。
【问题讨论】:
-
递归解码消息到底是什么意思?我很难弄清楚您的代码打算做什么。给我们一个将递归多次的输入,以及递归每个阶段的输出,或者 - 如果阶段太多 - 它在几个重要阶段的样子。
-
您以错误的方式使用
indexOf。它需要一个字符串或一个字符,并会在字符串中找到字符的位置。你交出某种职位。此位置值用作字符并导致msg.indexOf返回-1,因为在字符串中找不到该字符。 -
如果您可以使用 Java 8,请使用集合和 map/filter 方法以及 lambda。
-
某个方法试图获取一个不存在的字符串元素的值
标签: java string recursion substring indexof