这是我在这里的第一篇帖子,顺便说一句,我的老师给全班分配了一个程序,我们需要做一个回文程序,我能够做到,但是我想摆脱错误,请问向我解释为什么有错误,以及如何消除它?
import java.io.*;
public class AssignmentInCopro
{public static void main (String [] args) throws IOException
{BufferedReader x = new BufferedReader(new InputStreamReader(System.in));
String word = "";
System.out.print("Please enter the word you want to see in reverse: ");
word = x.readLine();
int wordLength = word.length();
while (wordLength >=0)
{
char letter = word.charAt(wordLength - 1);
System.out.print(letter);
wordLength--;
}
}
}
最佳答案
该错误在循环包括索引零时出现。如果wordLength
为零,那么您将查找charAt(-1)
并得到异常:
将您的代码更改为:
while (wordLength >0)
错误消失了。
关于java - 程序正在运行,但有错误,字符串索引超出范围:-1,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25708301/