user2932587
user2932587

Reputation:

Passing the size of an array to a method

I'm studying for my final in my computer science class and one of the practice programs the prof gave us to write asks us to write a method which will be passed the size of an array. We are then to prompt the user to enter numbers to fill the array, and lastly return the loaded array. I'm pretty sure I can do the loading and returning the array part, but I've never had to pass an array size to a method before, any ideas how I would do this?

I know the method header would be something like this:

public static double[] loadScores(*I don't know what would go in here*) {

Upvotes: 0

Views: 62

Answers (2)

Julián Urbano
Julián Urbano

Reputation: 8488

public static double[] loadScores(int size) {
  double[] array = new double[size];
  // ask for numbers and fill array
  return array;
}

Upvotes: 1

Óscar López
Óscar López

Reputation: 235984

Just pass the size of the array as an int parameter:

public static double[] loadScores(int n)

Inside the method you can create a new array of that size, as a local variable which will be returned at the end:

double[] array = new double[n];

Upvotes: 5

Related Questions