I am beginner in Java and I am trying to make a simple sorting program. But I am having trouble while giving input to an array that has to sorted.
Here I have 2 files App.java
and Sorting.java
App.java
public class App {
public static void main(String[] args) throws Exception {
Sorting s = new Sorting();
s.getData();
s.showData();
}
}
Sorting.java
import java.util.Scanner;
public class Sorting {
private
int n;
int[] array = new int[n];
public
void getData(){
Scanner input = new Scanner(System.in);
System.out.println("Enter the size of Array to be Sorted");
n = input.nextInt();
System.out.println("Enter elements of an array ");
for (int i = 0; i < n; i++) {
array[i] = input.nextInt();
}
}
void showData(){
for (int i = 0; i < n; i++) {
System.out.println("Sorted Array => "+ array[i]);
}
System.out.println(n);
}
}
But when I compile it and trying to give values to the array, I end-up with an error which says:-
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 ndex 0 out of bounds for length 0 at Sorting.getData(Sorting.java:16) at App.main(App.java:4)
It'll be great if someone can point me out that what's wrong I am doing ?