0

I am new to the Java language. I'm currently trying bubble sort with the concept of functions and user input method. Can anyone help me to solve this particular issue of not getting any output?

import java.util.*;

public class Bubble {
    public static void bubble_sort(int[] arr) {
        for (int turn = 0; turn < arr.length - 1; turn++) {
            for (int j = 0; j < arr.length - 1 - turn; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    static void print_array(int[] arr) {
        System.out.println("" + arr.length + "values:");
        for (int j: arr) {
            System.out.print(j + " ");
        }
    
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int[] arr = new int[0];
        int n;
        n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        bubble_sort(arr);
        print_array(arr);
    }
}

The modified code with error

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    Are providing data to read? Also `int[] arr = new int[0];` creates array which can't store anything. You should create that array *after* you know how many numbers you want to store in it. – Pshemo Aug 22 '22 at 20:13
  • Are you getting any errors? If so, please include a copy. I would expect an Array Index Out of Bounds error. – Old Dog Programmer Aug 22 '22 at 20:28
  • One way you can improve your code is to output a prompt for the user when expecting input: `System.out.print ("How many numbers will you enter? "); n = sc.nextInt();` `System.out.print ("("+i+") Enter a number >"); arr[i] = sc.nextint();` – Old Dog Programmer Aug 22 '22 at 20:33
  • 1
    See the comment from @Pshemo. You need to have `int [] arr = new int [n];` _after_ the user enters a valid value for `n`. `n` specifies the size of the array -- how many elements it will hold. `new int [0];` creates an array that cannot hold any number(s). – Old Dog Programmer Aug 25 '22 at 15:20

1 Answers1

0

To better understand the behaviour of such functions I suggest to modify the printing like this:

static void print_array(int[] arr) {
    System.out.println("" + arr.length + "values:");
    for (int j: arr) {
        System.out.print(j + " ");
    }

    System.out.println();
}
Queeg
  • 7,748
  • 1
  • 16
  • 42