I wanted to create a temporary array to store the input by the user and sort it to get the m smallest elements and refer to the original index of the originalArray and then print the index of the m smallest elements but when I run my code, all I get is -1
. My elements should not be out of bounds of the original array as it is taken from originalArray
. Why am I getting -1
?
import java.util.*; public class MinimumSelection { public static void main(String[] args) { //Array and variable declarations int[] originalArray; int[] tempArray; int tempValue; int lowestValue; int arrayLength; String elementValue; //Prompt the user for random numbers as an array input System.out.println("Please Enter your array length"); arrayLength = Integer.parseInt(new Scanner(System.in).nextLine()); //Input feeds as the length of the array as entered by user originalArray = new int[arrayLength]; //Storing the input value in temporary array which will be used to sort tempArray = new int[arrayLength]; //prompt user to enter elements of the orignial array for (int element = 0; element < originalArray.length; element++) { System.out.printf("\n Enter array elements %1$s: " + "\r\n", element + 1); elementValue = new Scanner(System.in).nextLine(); originalArray[element] = Integer.parseInt(elementValue); } System.arraycopy(originalArray, 0, tempArray, 0, originalArray.length); //Sorting the original array for (int write = 0; write < tempArray.length; write++) { for (int sort = 0; sort < tempArray.length - 1 - write; sort++) { if (tempArray[sort] > tempArray[sort + 1]) { tempValue = tempArray[sort + 1]; tempArray[sort + 1] = tempArray[sort]; tempArray[sort] = tempValue; } } } //promoting user to enter no. of smallest elements they want this program to display System.out.println("Please Enter number of smallest element"); lowestValue = Integer.parseInt(new Scanner(System.in).nextLine()); //display output System.out.println("Result :"); for (int loop = 0; loop < lowestValue; loop++) { int x = tempArray[loop]; int y = Arrays.asList(originalArray).indexOf(x); // Arrays.asList(array).indexOf(4); System.out.println((new Integer(y)).toString()); } new Scanner(System.in).nextLine(); } }