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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.