0

I am getting nullpointerexception when i call the putArray()and sortArray() methods. getArray() method works fine. when i print the array within getArray() method it is working. But i get null pointer exception when i print in putArray() method.I spent a lot of time figuring it out .Kindly help me resolve this. also suggest me any other better ways to write this code. Thank you.

import java.util.Scanner;
public class BubbleSort {
    int num;
    int[] arr;
    public void getArray() {
        System.out.print("Enter the total numberr of elements in the Array :  ");
        Scanner sc = new Scanner(System.in);
        num = sc.nextInt();
        int arr[] = new int[num];
        System.out.print("Enter " + num + " Elements  : ");
        for (int i = 0; i < num; i++) {
            arr[i] = sc.nextInt();
        }
    }
    public void putArray() {
        System.out.print("The Array is:  ");
        for (int i = 0; i < num; i++) {
            System.out.println(arr[i] + "  ");
        }
    }
    public void sortArray() {
        for (int i = 0; i < num; i++) {
            boolean flag = false;
            for (int j = 0; j < num - i - 1; 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];
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
        }
    }
    public static void main(String[] args) {
        BubbleSort b = new BubbleSort();
        b.getArray();
        b.putArray();
        b.sortArray();
        b.putArray();
    }
}
Harish93
  • 1
  • 4

1 Answers1

0

You are using arr variable in putArray() method and arr is not initialized.

arr = new int[num]; // Fix: Make this change in getArray method at line#9

There are two arr variable in the this code. You have initialized local variable in getArray() method and you are using class level arr array variable in putArray() method