简体   繁体   中英

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. Ie myNumbers[4] = 4.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM