Kenta Goto Kenta Goto - 2 years ago 125
Java Question

Java run-time error

I am running this code:

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

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

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};

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 Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download