I am an absolute beginner to Java. Recently i started to write a code in Java to sort the 5 elements of an array. The user will input the array elements. It complies the code and runs the program. but as soon as i finish inputting the array elemts, the program crashes! Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int[] arr;
arr = new int[5];
System.out.println("Enter the 5 elemnts in the array");
for(int i=0; i<5; i++)
arr[i] = in.nextInt();
int temp;
for(int i=0; i<5; i++)
{
temp = arr[i+1];
for(int j=i+1; j>=0; j--)
{
if(arr[i] > temp)
{
arr[j] = temp;
arr[i] = arr[j];
}
}
}
}
}
it throws an error which is something like: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Main.main(Main.java:16) i just cannot read and understand the error!
ArrayIndexOutOfBoundsException? I suggest you do that, and read the arrays tutorial. Next, think about the value ofi+1across all the values ofithat you'll be using...Main.Java:16tells you the line the error is on, and the name of the exception,ArrayIndexOutOfBoundstells you that the number in the array that you're trying to access doesn't exist.