线程主java.lang.arrayindexoutofboundsexception中的异常1

时间:2016-05-02 01:49:30

标签: arrays

我必须制作一个java程序,确定给定的数字是否为capicua(131,12121,13431),从最后一位到最初的数字是否相同。但它给了我错误,在第23行(而(i> = 0).....)问题是我怎么能把数组调用到那个。请帮助我真的很难过:c。这是代码:

public class Capi {
    /**
     *
     **/
    public static int num(int a) { // counting digits from the number
    int n = 0;
    while(a>=10) {    a = a/10;
            n = n+1;
           }
    return n;
    }
    public static boolean det(int a, int n) {
    int z = a;
    double y =0;
    n = n-1;
    int i = 0;
    int x[] = new int[n];
    for(i=0; i<x.length; i++) { // saving the digits into x[i]
        x[i] = a%10;
        a = a/10;
        }
    while(i>=0) { y = x[i]*Math.pow(10,n-1); // calling the digits x[i],x[i-1]   untill it gets 0
        i = i - 1;
        n = n -1;
            }
    double num1= y + a*Math.pow(10,n);
    if(num1 == z) { return true; }
    else { return false; }
    }
} 

1 个答案:

答案 0 :(得分:0)

我觉得问题是在尝试while(i>=0)之前,i的值设置为x.length。因此,在运行循环之前我已经添加了i--

看看以下是否有效。

public class Capi {

public static int num(int a) { // counting digits from the number
    int n = 0;
    while(a>=10) {
        a = a/10;
        n = n+1;
    }
    return n;
}

public static boolean det(int a, int n) {
    int z = a;
    double y = 0;
    n = n-1;
    int i = 0;
    int x[] = new int[n];

    for(i=0; i<x.length; i++) { // saving the digits into x[i]
        x[i] = a%10;
        a = a/10;
    }

    //i is now set to x.length, thus decrement it as index runs from 0 to x.length-1
    i=i-1;

    while(i>=0) {
        y = x[i]*Math.pow(10,n-1); // calling the digits x[i],x[i-1]   untill it gets 0
        i = i - 1;
        n = n -1;
    }

    double num1= y + a*Math.pow(10,n);
    if(num1 == z) {
        return true;
    }
    else {
        return false;
    }
}

}