jeudi 23 mars 2017

Array index out of bounds with random generator

I am working on my home work and have an issue I cannot sort. All of this I created and it compiles fine until I tried to test it in the main. It is giving me the error in "

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1712741702
    at Test.arrayGen(Test.java:45)
    at Test.main(Test.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
".  

Here are the methods I created, one for the generation of the arrays and the sort as well as a counter to track the number of changes. Any help is appreciated.

import java.util.*;

public class Test {

    public static int selectionSort(int[] data) {

        int min;
        int temp;
        int counter = 0;

        for (int index = 0; index < data.length-1; index++) {

            min = index;
  /* Find the minimum element from position index */
            for (int scan = index + 1; scan < data.length; scan++) {
                counter++;
                if (data[scan] < (data[min])) min = scan;
            }

         /* Swap the values */
                temp = data[min];
                data[min] = data[index];
                data[index] = temp;

        }
        return counter;
    }

    public static int[] arrayGen(int max) {
        int top = 100;
        int bottom = 0;
        int listInts;
        Random random = new Random();

        top = 100;

        int[] myList = new int[max];

        for (int i = 0; i < max; i++) {
            myList[i] = random.nextInt(top - bottom);
            listInts = random.nextInt();
            System.out.println(myList[ listInts]);

        }
        return myList;
    }


   public static void main(String[] args) {
        selectionSort(arrayGen(5));

    }

}




Aucun commentaire:

Enregistrer un commentaire