0

exception showing in java code......at statement----- if(a[j]>a[j+1])..... please help please help

package arrays; import java.util.Scanner; public class array { public static void main(String[] args){ int n; System.out.println("enter n"); Scanner myvar=new Scanner(System.in); n=myvar.nextInt(); int arr[]= new int[n]; for(int i=0;i<arr.length;i++) arr[i]=myvar.nextInt(); System.out.println("\n your array is ..."); for(int t:arr) System.out.println("\n "+t); System.out.println(arr[1+1]); for(int i=0;i<(arr.length)-1;i++) {for(int j=0;j<arr.length;j++) { if(arr[j]>arr[j+1]) { arr[j]=arr[j]+arr[j+1]; arr[j+1]=arr[j]-arr[j+1]; arr[j]=arr[j]-arr[j+1]; } } } System.out.println("\n your sorted array is ..."); for(int t:arr) System.out.println("\n "+t); } }

28th Nov 2017, 10:25 AM
Gokul Krishna
Gokul Krishna - avatar
5 Antworten
+ 2
You are not checking array boundaries. If the array is 10 elements you try accessing arr[10]
28th Nov 2017, 10:47 AM
Josef Held
Josef Held - avatar
0
I didn't get your point
28th Nov 2017, 10:48 AM
Gokul Krishna
Gokul Krishna - avatar
0
I got your point
28th Nov 2017, 10:49 AM
Gokul Krishna
Gokul Krishna - avatar
0
Thanks a lot sir......
28th Nov 2017, 10:50 AM
Gokul Krishna
Gokul Krishna - avatar
0
You are welcome!
28th Nov 2017, 10:51 AM
Josef Held
Josef Held - avatar