在我的學校任務中,我必須製作遞歸方法,並且只能使用.charAt,.indexOf,.substring,.toLowerCase,.concat和其他一些我擁有的方法在代碼中使用我的代碼中發生StringIndexOutOfBoundsException的原因是什麼
這是代碼
/*
* 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)
我已經與方法擺弄周圍用於清潔字符to後帽子不是字母或數字,但系統似乎喜歡從字符串到字符的轉移。
我翻轉方法的工作,但我的清洗經常遇到錯誤的地方是超出範圍。我曾嘗試添加很多東西以確保它在範圍內,但這隻會增加問題。
你知道,一切都在正確的0開始索引? – WIR3D
是;我在某個地方搞砸了嗎? –
你的第一個電話來清洗輸入和它的長度傳球,然後試圖做一個'的charAt(長)',這是從來沒有的法律,因爲有效的指標是'0 ...長度1'。 – azurefrog