0

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 ?

Uttam
  • 718
  • 6
  • 19
  • 1
    You create the array of size n = 0 before reading the value you're entering. – m0skit0 Aug 08 '21 at 10:45
  • 1
    Your array will be initialized to have size zero as there is no value. You should initialize the array *after* getting n from the user – g00se Aug 08 '21 at 10:46

1 Answers1

1

Your array is of size 0:

int n;  // same as: int n = 0;
int[] array = new int[n];

That's why array[i] = input.nextInt(); will always give an error; you cannot index into an empty array.

ruohola
  • 21,987
  • 6
  • 62
  • 97