0

Java error help : exception in thread main java.lang.arrayindexoutofboundsexception index 5 out of bounds for length 5

im a beginner in java I been having problems with this method, I keep getting the error (exception in thread main java.lang.arrayindexoutofboundsexception index 5 out of bounds for length 5) for my loop in the method body. I cant figure out how to fix this problems the method gets the parameter int size to get the erray size from another array into a new one. it then ask the user for 5 integer ages and then the loop stores the values and displays the array values to the user. code: public static int[] getIntArrayFromUser(int size) { Scanner myScanner = new Scanner(System.in); int tempArray[] = new int[size]; System.out.print("please enter 5 ages below one at a time: "); tempArray[size] = myScanner.nextInt(); for (int i = 0; i <size;i++) { System.out.println(tempArray[i]); } return tempArray; }

27th Nov 2020, 4:19 AM
TheKaiserUltra V1
TheKaiserUltra V1 - avatar
1 Antwort
+ 3
public static int[] getIntArrayFromUser(int size) { Scanner myScanner = new Scanner(System.in); int tempArray[] = new int[size]; System.out.print("please enter 5 ages below one at a time: "); //tempArray[size] = myScanner.nextInt(); for (int i = 0; i <size;i++) { tempArray[i] = myScanner.nextInt(); System.out.println(tempArray[i]); } return tempArray; }
27th Nov 2020, 4:26 AM
Ipang