I'd like to know why I got these errors and how to fix it:

Main.java:12: error: '.class' expected
        populateArray(int[] aRand);
                            ^
Main.java:12: error: ';' expected
        populateArray(int[] aRand);

The instructions I was given are in the comments and I just followed what I believe what the instructions meant. I thought maybe I should do populateArray(); in the main method, but it wouldn't match the signature of public void populateArray(int[] array){}.

import java.util.Random;

public class Main {
    public static void main(String args[])
    {
    /*
    (a) Create an array of integers called aRand of capacity 20 and initialize its entries to 0. 
    */
        int aRand[] = new int[20];

        populateArray(int[] aRand);

    }

    /*
    (b) Populate the array in a method called populateArray(int[] array) where array is the one you want to populate. 
    This method returns void. 
    */
        public void populateArray(int[] array){
          Random rand = new Random();
          for (int i=0; i<array.length; i++){
            array[i] = rand.nextInt();
            System.out.println(array[i]);
          }
        }
}

1 Answers

0
Jack Ryan On Best Solutions

Just a couple small things!

First, you already declared populateArray as a method that takes an int[], so you do not need to do so when you actually call the method.

Second, you cannot call a non-static method from a static context. Since your main method is static, you cannot call the non-static method populateArray within it. For your purposes, it should be fine to just declare populateArray as a static method.

import java.util.Random;

public class Main {
    public static void main(String args[])
    {
    /*
    (a) Create an array of integers called aRand of capacity 20 and initialize its entries to 0. 
    */
        int aRand[] = new int[20];

        populateArray(aRand); // We already know aRand is an int[]

    }

    /*
    (b) Populate the array in a method called populateArray(int[] array) where array is the one you want to populate. 
    This method returns void. 
    */
    public static void populateArray(int[] array){
        Random rand = new Random();
        for (int i=0; i<array.length; i++){
            array[i] = rand.nextInt();
            System.out.println(array[i]);
        }
    }
}

For reference, here as a helpful StackOverflow answer that discusses when you should use static vs. instance methods: Java: when to use static methods.