【发布时间】:2021-11-18 15:19:19
【问题描述】:
我正在尝试使用在 createArray 方法中创建的二维数组“myArray” - 在程序的所有其他方法中。我查看了与此类似的其他一些堆栈溢出答案,但我尝试过的任何方法都没有奏效。每次我尝试将数组传递给其他方法时,都无法解析。
这是我的代码:
import java.lang.Math;
import java.util.Scanner;
public class RandomArray {
public static void main(String[] args) {
createArray();
calculateVariables();
callArray();
}
public static void createArray(){
Scanner scan = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scan.nextInt();
System.out.print("Enter number of columns: ");
int columns = scan.nextInt();
int count = 0;
int[][] myArray = new int[rows][columns];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < columns; col++) {
myArray[row][col] = (int) (Math.random() * 100);
System.out.print(myArray[row][col] + "\t");
if (rows > 0) {
count++;
}
}
System.out.println();
System.out.println();
System.out.println("The number of elements in the array: " + count);
}
}
public static void calculateVariables(){
int sum = 0;
int min = myArray[0][0];
int max = myArray[0][0];
int below50 = 0;
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray.length; j++) {
if (max < myArray[i][j]) {
max = myArray[i][j];
}
if (min > myArray[i][j]) {
min = myArray[i][j];
}
sum = sum + myArray[i][j];
if (myArray[i][j] < 50) {
below50++;
}
}
}
System.out.println("The average number is: " + sum / count);
System.out.println("the min is " + min);
System.out.println("the max is " + max);
System.out.println("the number of entries below 50 is: " + below50);
System.out.println();
}
public static void callArray(){
Scanner scan2 = new Scanner(System.in);
System.out.print("Enter a row number: ");
int row1 = scan2.nextInt();
System.out.print("Enter a column number: ");
int col1 = scan2.nextInt();
if ((row1 > myArray.length) && (col1 > myArray.length)) {
System.out.println("Sorry, I cant retrieve that value! You entered a bad index.");
}
if ((row1 < 0) && (col1 < 0)) {
System.out.println("Sorry, I cant retrieve that value! You entered a bad index.");
} else System.out.println("The entry at that row and column is: " + myArray[row1][col1]);
}
}
}
【问题讨论】:
-
您永远不会将数组传递给任何其他方法。由于数组被定义为方法局部变量,其他方法无法访问它,除非它被传递
-
显而易见的答案,特别是对于名为“创建数组”的方法,是返回您刚刚创建的数组:
int[][] createArray(){...
标签: java arrays multidimensional-array methods