stupidmoron
stupidmoron

Reputation: 1

Why is my array not found when it is so there?

My jdk compiler keeps telling me that my array, called nums, is not found when it is so there! What gives? Please forgive my ignorance; I am just learning. Anyway, my code is listed below.

import java.util.Random;
import java.util.Arrays;

public class BubbleSort {
    public static void main(String[] args) {
        Random rand = new Random();
        int[] nums = new int[10];
        for (int i = 0; i < nums.length; i++)
            nums[i] = rand.nextInt(100);
        System.out.println("Unsorted array: " + Arrays.toString(nums));
        sort();
        System.out.println("Sorted array: " + Arrays.toString(nums));
    }
    
    public static void sort() {
        int temp;
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = 0; j < nums.length - i - 1; j++) {
                if (nums[j] > nums[j+1]) {
                    temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
    }
}

Upvotes: 0

Views: 79

Answers (1)

Unmitigated
Unmitigated

Reputation: 89234

nums is not visible outside of the method in which it was defined (main). Pass it as an argument to sort instead.

Change the signature of sort to accept an array parameter:

public static void sort(int[] nums)

Pass nums to sort in main:

sort(nums);

Upvotes: 1

Related Questions