Привет, я продолжаю получать эту ошибку всякий раз, когда пытаюсь ввести пустую строку. Все остальное пока работает, и если я поставлю пробел внутри строки, все сработает. Я знаю, что это очень придирчиво, но мне очень любопытно, что мне делать в этой ситуации, чтобы убедиться, что он возвращает только пустую строку.
**> HW2.nthWord(2,"")
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at HW2.nthWord(HW2.java:124)**
Я создал специальный экземпляр для ввода этого значения, но он все еще не работает.
Что мне нужно, чтобы исправить это?
/*nthWord takes an int and a String as input and returns a String:
The input int represents a number n that is assumed to be positive, and the output string
contains every nth word of the input string, starting with the first word, separated by a single space.
For this method, a word is defined to be a sequence of non-space characters.
There should be no space at the end of the output string.
*/
public static String nthWord( int number, String input ){
StringBuilder create = new StringBuilder();
int totalspaces = 0; //This is to hold a count of the number of spaces in a String
if ( number == 0){
return input;
}
if (input == ""){
return input;
}
else{
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
for( int i = 0; i < input.length() - 1 ; i = i + 1){
if (input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
if ( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
if (totalspaces % number == 0 && totalspaces != 0){
create.append(' ');
for(int j = i+1; input.charAt(j) != ' ' && j < input.length(); j = j+1){
create.append(input.charAt(j));
i = j;
}
}
}
}
return create.toString();
}
}




Я заметил несколько вещей
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
Этот цикл будет продолжать добавлять символы «ввода», пока не достигнет символа пробела. Если ввод не содержит символа пробела, то этот цикл выйдет за пределы длины ввода и вызовет ошибку. Вы можете захотеть что-то вроде:
for(int i = 0; i < input.length(); i = i + 1){
if (input.charAt(i) == ' ' ){
break;
} else {
create.append(input.charAt(i));
}
}
Кроме того, когда вы доберетесь до линии:
if (input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
вы уже знаете, что i < input.length() - 1, потому что вы находитесь в цикле for. Вы можете изменить эту строку на:
if (input.charAt(i) == ' ' && input.charAt(i+1) != ' '){
По той же причине ваш следующий раздел:
if ( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
можно изменить на
if ( i != input.length()-1 ){
totalspaces = totalspaces + 1;
}
Кроме того, я заметил, что вы, возможно, усложняете задачу. Проблема будет намного проще, если вы решите ее в одном цикле for.
for(int i = 0; i < input.length(); i = i + 1){
if ( x ) //x is some code that determines if you are part of the nth word
create.append(input.charAt(i));
}
input == ""это начало ваших проблем. Это неправильный способ сравнения строк.