开发者

Reversing Integer Value

I cannot figure this o开发者_如何学运维ut. This is for homework. I need to create a method that reverses an integer that is passed to it. I've now been able to fix the outofBounds error in the for loop thanks to everyone's input. The integer that is passed into the method can be of any length. And I have to return an integer instead of an array or string. But now I get an 'Unresolved compilation problem: Syntax error on token "[", Expression expected after this token' on the int u = backInt[]; line. But I have no idea what to put in the []'s. I haven't been able to find a way to convert an Integer array to an integer so I can pass the integer back, so I'm lost. Here is the code that I have so far:

public static int reverseIt(int x){

    int y = String.valueOf(x).length();
    int[] backInt = new int [y];
    for(int z = 0; z < y; z++){
        x %=10;
        backInt[z] = x;
        x /= 10;
    }
            int u = backInt[];
            return u;


    return -1;

}


You start with z=0 and end with z=y. That's y+1 times through the loop, but your array is correctly only y elements long, so the exception occurs on the last iteration of the loop when you try to write to the nonexistent element. By that time, though, x should already be zero because you've processed all y digits, so your stopping condition should be z<y instead of z<=y.


You're going too far in your loop. It should be:

for(int z = 0; z < y; z++) {

...instead.

Take the input 12 as an example. It's two characters long, so backInt has a length of 2. When you go through the loop, you're iterating through values of z of 0, 1, and 2. What's the value of backInt[2] when backInt only has two elements in it?

Edit: Your code will also break for, say, 2147483646, because your resulting integer will be too large for the Integer type. But that's beside the point here.


Java arrays are 0-indexed. What that means is that if you do int[] arr = new int[10], you create an integer array that can hold ten ints, and the first int is stored in arr[0], the second in arr[1], and the last in arr[10-1], which is arr[9].

To fix your code, change z <= y to z < y. In the future, just remember that if you create an array for n objects, then you can access them by arr[0], arr[1]... arr[n-1], but accessing arr[n] will throw an OutOfBounds exception.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜