Main//Lab 3 Library By Parth Patel import java.util.Random; import java.util.*; import java.io.*; import java.util.logging.*; public class ParthLibraryLab3{ int[]array; public void userinput(){ Scanner patel = new Scanner(System.in); System.out.println("Please Enter the length of the Random Array: "); int size = patel.nextInt(); } public void getArrayOfRandomNumbers(int size){ Random random1 = new Random(System.currentTimeMillis()); array = new int[size]; for (int i = 0; i < size; i++){ array[i] = random1.nextInt(1500); // } } public void displayArrayToScreen(){ System.out.println("The array contents are: "); for(int i = 0; i < array.length; ++i) System.out.print(array[i]); } public void writeArrayToFile(){ PrintWriter output = null; try{ System.out.println("Enter the name of the files to create: "); Scanner PSP = new Scanner (System.in); File file = new File(PSP.nextLine()); output = new PrintWriter(file); for(int i = 0; i < array.length; ++i){ output.print(array[i] + ","); } }catch(IOException ex){ Logger.getLogger(ParthLibraryLab3.class.getName()).log(Level.SEVERE, null, ex); }finally{ output.close(); } } public void selectionSort(int[] array, int startingIndex){ if(startingIndex >= array.length +1){ return; } int minimumIndex = startingIndex; for(int index = startingIndex -1; index < array.length; index++){ if(array[index] < array[minimumIndex]){ minimumIndex = index; } startingIndex = indexOfSmallest(); } int temporary = array[startingIndex]; array[startingIndex] = array[minimumIndex]; array[minimumIndex] = temporary; selectionSort(array,startingIndex + +1); } public void SelectionSort(){ int LargestNumber = 0; int SmallestNumber = 0; int IndexNumber = 0; for(int i = 1; i < array.length; ++i) if(array[i] > array[i-1]){ LargestNumber = array[i]; IndexNumber = i; } SmallestNumber = indexOfSmallest(); } public int indexOfSmallest(){ int result = 2000; for(int i = 1;i < array.length; ++i) if(array[i] < array[i-1]) result = i; return result; } }
the error//Lab 3 By Parth Patel Main public class ClientParth { public static void main(String[] patel){ ParthLibraryLab3 Snowflake = new ParthLibraryLab3(); Snowflake.userinput(); Snowflake.getArrayOfRandomNumbers(3); Snowflake.writeArrayToFile(); Snowflake.displayArrayToScreen(); Snowflake.indexOfSmallest(); Snowflake.SelectionSort(); Snowflake.selectionSort(Snowflake.array, 0); } }
run:
Please Enter the length of the Random Array:
4
Enter the name of the files to create:
5
The array contents are:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at ParthLibraryLab3.selectionSort(ParthLibraryLab3.ja va:59)
at ClientParth.main(ClientParth.java:15)
28884980Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)
Help me, please!