0

i have some problem when i run my code . i tried using Bubble sort algorithm.

this is my code class = sort.java

package asaimenoop;
import java.util.Scanner;
public class sort
{
    int size,d,z,swap;
    int sortArr[] = new int[d];
    Scanner in = new Scanner(System.in);

    public void getData()
    {

    System.out.print("Enter how many data you want to enter : ");
    size = in.nextInt();

    for (int z = 0; z < size; z++)
    {
        System.out.print("Enter element at " + (z+1) + "th position : ");
        sortArr[z] = in.nextInt();
    }
}

    public void BubSort()
   {
        getData();

        for ( int z = 0; z < ( size -1 ); z++)
        {
            for (d = 0; d < size - z - 1; d++)
            {
                if ( sortArr[d] > sortArr[d+1])
                {
                    swap = sortArr[d];
                    sortArr[d] = sortArr[d+1];
                    sortArr[d+1] = swap;
            }   
        }     
    }
}

    public void Display()
    {
     BubSort();
     System.out.println("After Sorting");

     for (int z = 0; z < size; z++)
     {
                System.out.println(sortArr[z]);
     }
}     
}

and this is my main class class = Bubsort.java

    package asaimenoop;
    public class Bubsort
{
    public static void main (String[] args)
    {
       sort t = new sort();
       t.BubSort();
       t.Display();

    }
}

when i run my code , it get error :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at asaimenoop.sort.getData(sort.java:19)
    at asaimenoop.sort.BubSort(sort.java:25)
    at asaimenoop.Bubsort.main(Bubsort.java:9)

it stuck on when i want to enter the element position,

sortArr[z] = in.nextInt();

sorry for my bad english

Zaim
  • 11
  • 1
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – seenukarthi Mar 27 '16 at 06:23

1 Answers1

2

This code

int size,d,z,swap;
int sortArr[] = new int[d];

creates sortArr as an array of length zero because d is initialized to the default value of zero.

It has no elements. Therefore an attempt to access any element will throw the exception you are seeing.

You need to move the statement that allocates sortArr to after you know how many elements you need.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190