我正在尝试在main中创建一个数组,使其与在main之外的方法中创建的数组相同。我想不出任何办法这样做......
这是我的代码:
public class GRID {
public void createGrid() {
int N = StdIn.readInt();
int thisarray[][] = new int[N][N];
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
int n = (int) (Math.random() * 6 + 1);
thisarray[x][y] = n;
}
}
}
public static void main(String []args){
GRID g = new GRID();
int [][] newArray = //thisarray
}
}
答案 0 :(得分:1)
你在寻找这个答案吗?我已将方法的返回类型更改为int[][]
在main方法中,我们可以调用createGrid
方法来获取int[][]
public class GRID {
public int[][] createGrid() {
int N = StdIn.readInt();
int thisarray[][] = new int[N][N];
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
int n = (int) (Math.random() * 6 + 1);
thisarray[x][y] = n;
}
}
return thisarray;
}
public static void main(String []args){
GRID g = new GRID();
int [][] newArray = g.createGrid();
}
}
如果您希望newArray
基于N
,请将N
发送到createGrid
方法。为此,您必须在createGrid
方法中添加一个参数,如下所示。从StdIn.readInt()
方法
createGrid
public class GRID {
public int[][] createGrid(int N) {
int thisarray[][] = new int[N][N];
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
int n = (int) (Math.random() * 6 + 1);
thisarray[x][y] = n;
}
}
return thisarray;
}
public static void main(String []args){
GRID g = new GRID();
int [][] newArray = g.createGrid(StdIn.readInt()); //new array everytime on the basis of input value.
}
}
答案 1 :(得分:0)
将createGrid()的返回类型从void更改为int [] []
public class GRID
{
public int[][] createGrid() {
int N = StdIn.readInt();
int thisarray[][] = new int[N][N];
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
int n = (int) (Math.random() * 6 + 1);
thisarray[x][y] = n;
}
}
return thisarray;
}
public static void main(String []args)
{
GRID g = new GRID();
int [][] newArray = g.createGrid();
}
}
答案 2 :(得分:0)
让thisarray
成为该类的static
实例(因为它在static main
中使用)
public class GRID {
private static int[][] thisarray;
public void createGrid() {
int N = StdIn.readInt();
thisarray = new int[N][N];
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
int n = (int) (Math.random() * 6 + 1);
thisarray[x][y] = n;
}
}
}
public static void main(String []args){
GRID g = new GRID();
g.createGrid();
int [][] newArray = thisarray;
}
}
答案 3 :(得分:0)
在return thisarray;
方法中添加createGrid()
(同时将返回类型从void
更改为int[][]
),在主要内容中您将拥有:
int [][] newArray = g.createGrid()
答案 4 :(得分:0)
public class GRID {
//Declare your array here
private int thisarray[][];
public void createGrid() {
int N = StdIn.readInt();
thisarray[][] = new int[N][N];
for (int x = 0; x < N; x++) {
for (int y = 0; y < N; y++) {
int n = (int) (Math.random() * 6 + 1);
thisarray[x][y] = n;
}
}
}
public static void main(String []args){
GRID g = new GRID();
//Then you can use it in the main
int [][] newArray = thisarray;
}
}