程序正在运行,但有错误,字符串索引超出范围:-1

时间:2014-09-07 08:15:44

标签: java

这是我在这里的第一篇文章,顺便说一下,我的老师给了班级编程的任务,我们需要做一个回文程序,我能够做到但我想摆脱错误,你能解释一下为什么会有错误,我该如何摆脱它?

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--;
    }
    }
}

3 个答案:

答案 0 :(得分:1)

当你的循环包含索引零时,会出现错误。如果wordLength为零,那么您将查找charAt(-1)并获得例外:

将您的代码更改为:

while (wordLength >0)

错误消失了。

答案 1 :(得分:0)

 while (wordLength >=0)

当wordLength = 0时会导致错误,那么char letter = word.charAt(wordLength - 1);实际上是char letter = word.charAt(0 - 1);

while (wordLength >0)

这应该是条件,或者你可以像这样编写你的循环 -

int wordLength = word.length() - 1;
while (wordLength >=0){
    System.out.print(word.charAt(wordLength--));
}

答案 2 :(得分:0)

看看当wordlength实际上等于0时会发生什么// while(wordLength> = 0) 你试图在-1 //word.charAt(wordLength - 1);

访问char

用while(wordLength> 0)或while(wordLength> = 1)更改它

度过愉快的一天