В моем школьном назначении я должен сделать рекурсивные методы и использовать только .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)
Я возился с методом очищения символов т шляпа не являются буквами или цифрами, но система, похоже, пользуется передачей от строки к символу.
Мой метод перелистывания работает, но моя очистка всегда заканчивается ошибкой, когда она выходит за пределы допустимого диапазона. Я попытался добавить много вещей, чтобы убедиться, что он находится в зоне действия, но это просто добавляет проблемы.
Вы знаете, что все начинает индексироваться при 0 правильно? – WIR3D
Да; я что-то испортил? –
Ваш первый вызов для очистки проходит во входе и его длине, а затем пытается выполнить 'charAt (length)', который никогда не является законным, поскольку действительные индексы равны «0 ... length-1'. – azurefrog