Array out of bounds in java but it worked in C [duplicate]

Home / Uncategorized / Array out of bounds in java but it worked in C [duplicate]

Question:
This question already has an answer here:What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? 14 answers

hey guys i am getting this error i did the same in C and it worked but when i did it in java i am getting the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5" can you look into this –>
import java.util.Scanner;

class sort {

public static void main(String args[]) {

Scanner obj = new Scanner(System.in);
int a[] = new int[5];
int i, j;
int temp;

System.out.println("Enter the elements of array : ");

for (i = 0; i < 5; i++) { a[i] = obj.nextInt(); } for (i = 0; i < 5; i++) for (j = 0; j < 5; j++) { if (a[i + 1] < a[i]) { temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } for (i = 0; i < 5; i++) System.out.println("n" + a[i]); } }


Answer:
Your problem is here:for (i = 0; i < 5; i++) for (j = 0; j < 5; j++) { // When `i` == `4` this accesses `a[5]` which does not exist. if (a[i + 1] < a[i]) { Read more

Leave a Reply

Your email address will not be published. Required fields are marked *