JAVA数组索引绑定错误与工作代码

时间:2018-01-20 21:53:01

标签: java arrays

这是代码和评论。这是一个工作但它也产生一个ArrayIndexOutOfBoundsException:-1错误,当输入是"雷达"," hanah"或任何可反转的字符串:

public static void main(String[] args) {
    //a sample code to test if newString variable could be written in reverse order
    int i,j,counter=0;
    boolean loopControl=true;
    String newString = "hanah";                 //here goes the sample RADAR string or HANAH ,etc
    String[] stringArray = new String[newString.length()];  //making an array with the dimension of the length of given string

    for(i=0;i<newString.length();i++) {                         //a loop to assign every character of newString 
        stringArray[i]=newString.substring(i,i+1);              //to a array called stringArray using .substring()
    }                                                           //method
    j=newString.length()-1;                                     //j variable as an index for the last element of stringArray
    while (loopControl) {
        for(i=0;i<newString.length();i++) {                     //a loop to compare the elements of stringArray
            if(stringArray[i].equals(stringArray[j])) {         //to each other in reverse order
                j--;
                counter++;                                      //this counts the true values and will help to determine
            }                                                   // if all elements of stringArray are in right position 

                else {
                    loopControl=false;
                    System.out.println("Not reversable!!");
                    break;
                }       
        }
        if(counter==newString.length()) {
            System.out.println("TRUEEEEE REVERSABLE");
        }
    }
}

0 个答案:

没有答案