I've got a bit of an issue when I'm trying to add integers to my array in Java. The task is from CodeWars and it is to take an integer such as 12345 and return it as a reversed array of integers like {5, 4, 3, 2, 1}.
Now, my code compiles and runs on eclipse, even though the array doesn't get returned as it should but I think code wars has an edited toString class for that.
Anyways, here is my code:
package CodeWars;
import java.lang.reflect.Array;
public class Digitize
{
public static void main(String[] args)
{
System.out.println(digitize(472837428));
}
public static int[] digitize(long n)
{
String conv = Long.toString(n);
int[] result = new int[conv.length()];
for(int i = 0, index = conv.length(); i == conv.length(); i++, index--)
{
int temp = Character.getNumericValue(conv.charAt(i));
Array.setInt(result, index, temp);
}
return result;
}
}
And since code wars for some reason doesn't want us to have main methods, here is what I pasted there:
import java.util.*;
public class Kata
{
public static int[] digitize(long n)
{
String conv = Long.toString(n);
int[] result = new int[conv.length()];
for(int i = 0, index = conv.length(); i == conv.length(); i++, index--)
{
int temp = Character.getNumericValue(conv.charAt(i));
Array.setInt(result, index, temp);
}
return result;
}
}
That code then runs on their checking method here:
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class DigitizeExampleTests {
@Test
public void tests() {
assertArrayEquals(new int[] {1, 3, 2, 5, 3}, Kata.digitize(35231));
}
}
So when i run the code in CodeWars I get this thrown at me:
/workspace/java/src/Kata.java:12: error: cannot find symbol
Array.setInt(result, index, temp);
^
symbol: variable Array
location: class Kata
1 error
I've looked all over google but all other issues with can't find symbol have been misspelled classes or method calls. Any ideas? Also as a beginner Java learner, if you see any other ways to improve the code please do let me know.
Thanks
forloop condition is wrong (the condition is when to keep going, not when to stop), and yourindexis wrong. You'd get anArrayIndexOutOfBoundsExceptionon the first iteration of the loop, except the loop will never run due to the condition being wrong. Also, as other have said, just access the array directly without reflection.