Click here to Skip to main content
15,893,790 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello, I am trying to sort 2d array program using bubble sort but when I compile the program, it runs to the specific part of the program, It prints out the 2d array, But, when it reaches to the sorting part, I get an error, "java.lang.Arrayindexoutofboundsexception:3". Please tell me how to get rid of this error. See the code below.

What I have tried:

import java.util.Random;
import java.util.Scanner;

public class arrays {

	public static void main(String[] args) {
		
		Random ran= new Random();
	
		Scanner scan = new Scanner(System.in);
		
		int num,secnum,temp,i,j,k;
		
		System.out.println("Please enter a num.");
		
		
		
		num= scan.nextInt();
		
		System.out.println("Please enter another value.");
		
		secnum = scan.nextInt();
		
		int arrayi[][] = new int[num][secnum];
		
		
		for( i =0; i< num ; i++) {
			
			for( j =0; j< secnum; j++) {
				
				arrayi[i][j]= ran.nextInt(100);
				
			}
		}
		
		System.out.println("The array is below:");
		
for(i =0; i< num ; i++) {
			
			for( j =0; j< secnum; j++) {
				
				System.out.print(arrayi[i][j] + " ");
				
			}
			System.out.println();
		}
for( i =0; i< num ; i++) {
	
	for( j =0; j< secnum; j++) {
		
	for( k=0; k <secnum; k++) {
		if(arrayi[i][k] > arrayi[i][k+1] ) {
			temp = arrayi[i][k];
			arrayi[i][k] = arrayi[i][k+1];
			arrayi[i][k+1] = temp;
		}
	}
		
	}
	
}
System.out.println("Sorted array is below:");
for( i =0; i< num ; i++) {
	
	for( j =0; j< secnum; j++) {
		
		System.out.print(arrayi[i][j] + " ");
		
	}
	System.out.println();
}
		
scan.close();
	}
	

}
Posted
Updated 31-Aug-18 5:43am

1 solution

for( k=0; k < secnum; k++) {
    if(arrayi[i][k] > arrayi[i][k+1] )


The length of array[i] is secnum. Therefore, the maximum index you can access is secnum - 1.

When your loop reaches the final iteration, k = secnum - 1, so you cannot access arrayi[i][k + 1], because that is outside the bounds of the array.

(You could have easily found this out for yourself by using the debugger.)

Change your loop to:
for ( k=0; k < secnum - 1; k++) {
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900