I cannot figure this out. 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=0and end withz=y. That’sy+1times through the loop, but your array is correctly onlyyelements 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,xshould already be zero because you’ve processed allydigits, so your stopping condition should bez<yinstead ofz<=y.