2016-05-02 42 views
0

好吧,我必须做一个Java程序,确定如果给定的数字是capicua(131,12121,13431)从最后到最初的数字相同的数字。但它给了我错误,在第23行(while(i> = 0).....)问题是我怎样才能将数组调用到whileh中。请帮助我真的很伤心:c。下面是代码:在主线程中的异常main java.lang.arrayIndexoutofboundsexception 1

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

请不要转储的代码。格式化并发布您的问题。 – randominstanceOfLivingThing

+0

嘿迈克。哪一行抛出异常?你想用这个代码来完成什么?您的目标不明确,并且知道代码应该做什么将有助于诊断问题。 –

+0

请使用{code}代码段添加代码。其他人更容易帮忙。 – MSameer

回答

0

我觉得这个问题是我的值设置为x.length,尝试while(i>=0)之前。因此,在运行循环之前,我已添加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; 
    } 
} 

}

+0

嗨,我不认为它会成为事情,因为它从0到 Mike

+0

@Mike,The for循环终止时的值是'x.length或n'。 java中的数组索引从0到array.length -1。因此,你只能执行'x [0]到x [x.length-1]',但在你的情况下'i = x.length',所以它会抛出出界异常的索引。看看这个http://ideone.com/qWmPMW。希望这有助于,享受! – MSameer

+0

什么.... OMG!你说得对,男人如果你在这里我会给你一个吻,谢谢你,谢谢谢谢谢谢Math.pow(谢谢你) srry im rlly noob at programming。你是对的。! – Mike

相关问题