Kenta Goto Kenta Goto - 7 months ago 18
Java Question

Java run-time error

I am running this code:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;


class Ideone
{
public static int solution(int X, int[] A) {
int[] myNumbers = new int[X];
for (int i = 0; i < A.length; i++){
myNumbers[A[i]] = A[i];

}
return -1;

}

public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int[] A = {1,3,1,4,2,3,5,4};
System.out.println(solution(5,A));
}
}


However, I get a run-time error. I don't know why. I need to store the value of the array in A in another array with that value as an index. I.e myNumbers[4] = 4.

Answer

myNumber indexes goes from 0 to 4, at some point you are trying to access the index 5 which does not exist

So either pass 6 to solution or use myNumber[A[i]-1] (so myNumber[0] = 1)

Comments