这是我在这里发表的第一篇文章,顺便说一句,我的老师给全类布置了一个编程作业,其中我们需要做一个回文程序,我能够做到,但我想摆脱这个错误,您能解释一下为什么会出现错误,以及如何消除它吗?
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/