【发布时间】:2015-08-03 19:32:40
【问题描述】:
在Java中,如何调用带有数组参数和多个其他参数的方法?在这种情况下,我尝试在main() 方法中调用方法generateRandoms(int[] numbers, int low, int high, int count){}。
import java.util.Arrays;
import java.util.Scanner;
import java.util.Random;
public class Statistics_19711 {
static Scanner input = new Scanner(System.in);
public static void generateRandoms(int[] numbers, int low, int high, int count){ // semi-done
//Generate random numbers within the range [low, high] and store them in numbers array
low = 1;
System.out.println("Creating 500 random numbers from 1 to " + count + ":");
Random rand = new Random();
if (high > 0 && high <= 100000) {
for (int i = 0; i < numbers.length; i++){
numbers[i] = rand.nextInt();
System.out.print(i+ ((i-(0-1))%10==0 ? "\n" : " "));
}
} else {
System.out.println("Input outside of range. Try Again.");
}
Arrays.sort(numbers);
}
public static void main(String[] args) {
//the main() method should call the above methods. The main() method is then only method that does the input and output operation.
System.out.println("This program creates random numbers and calculates some statistics.");
System.out.println("Enter the upper limit of all generated random numbers:");
int high = input.nextInt();
System.out.println("Enter the count(maximum of 100000) of random numbers:");
int count = input.nextInt();
generateRandoms(numbers, 1, high, count);
}
}
int[] 数字是方法generateRandoms() 中的局部变量。我们如何在main() 中调用这个方法,并在不声明的情况下传递一个数组参数?
【问题讨论】:
-
“不声明任何”实际上是什么意思?
-
你会得到错误,因为你从来没有在你的 main 方法中声明“数字”,你也没有给“数字”数组一个大小。
标签: java arrays methods parameters