gpt4 book ai didi

java - 我的代码中出现 StringIndexOutOfBoundsException 的原因是什么

转载 作者:行者123 更新时间:2023-11-29 04:56:04 31 4
gpt4 key购买 nike

在我的学校作业中,我必须制作递归方法并且只能使用 .charAt、.indexOf、.substring、.toLowerCase、.concat 和我在代码中使用的其他一些方法

这是代码

/*
* Lab to perform different functions on Strings
* all methods are static
* only two methods should be public
* all other methods are internal (only used in the class)
*/

package stringutil;

/**
* @author [REDACTED]
*/

public class StringUtil {

public static boolean inOut(String input){//the argument is in main
int len = input.length();
boolean test;

input = input.toLowerCase();

//call the cleaners
input = StringUtil.cleanse(input, len);

//this is le final product
String reverse = StringUtil.flip(input);
test = input.equals(reverse);

return test;
}

private static String cleanse(String raw, int count){
if (count < 0)
return ("");
//this means that there was invalid punctuation
else{
char ch;
ch = raw.charAt(count);

if (ch >= 97 && ch <= 122 || ch >= 48 && ch<= 57){
//call method again with count-1 | string is same
return cleanse(raw, count-1);
}
else{ //character ain't ok yo
if (raw.indexOf(count) == -1){
raw = raw.substring(raw.length()-count, count-1);
}
else
raw = raw.substring(0,count-1).concat(raw.substring(count+1));
return cleanse(raw, count);
}
}
}

public static String flip(String input){
String newer;
// base case
if (input.length() == 1){
return input;
}
else{
//take the last letter and make it the new start
newer = input.substring(input.length()-1);
input = input.substring(0, input.length()-1);
return newer + flip(input);
}
//input = newer +
// flip(input.substring(0, input.length()-1));
}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {
// TODO code application logic here
System.out.println(StringUtil.flip("aashf"));
System.out.println(StringUtil.inOut("what, t;haw"));
}
}

所以我在运行后得到了这个

fhsaa
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
at java.lang.String.charAt(String.java:646)
at stringutil.StringUtil.cleanse(StringUtil.java:36)
at stringutil.StringUtil.inOut(StringUtil.java:21)
at stringutil.StringUtil.main(StringUtil.java:78)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

我一直在研究清除不是字母或数字的字符的方法,但系统似乎很喜欢从字符串到字符的转换。

我的翻转方法有效,但我的清理总是在超出范围时出错。我尝试添加很多东西以确保它在范围内,但这只会增加问题。

最佳答案

是的,字符串的 .length() 返回字符串中的数量或字符,因此您总是检查出边界,因为您需要在获取长度后减一,以免越界因为 .charAt() 在特定位置返回字母

关于java - 我的代码中出现 StringIndexOutOfBoundsException 的原因是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724744/

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