I have to make an array. Unfortunately I cannot figure something out. My problem: I want to make an array (two dimensional) and declare the size of the array in a method. BUT, here is my real problem, I want to use that array in other methods.
I tried to make an array in the class itself but then it is already declared and I cannot change it anymore.
This is the thing: I need an array whose size I can set myself. After that I want another method which can calculate something in an array. I also need another method to do something else in that array.
So my question is: How do I declare an array and make use of it in other methods? My code is on the bottom.
Hopefully it is explained good enough for you guys to help me.
public class Operations
{
public final int SET = 1;
int rows;
int cols;
int objects;
int times;
int doubles = 0;
int empty = 0;
int world[][] = new int[rows][cols];
public void print()
{
System.out.println(rows);
System.out.println(cols);
System.out.println(objects);
System.out.println(times);
}
public void setParameters(int rows, int cols, int objects, int times)
{
this.rows = rows;
this.cols = cols;
this.objects = objects;
this.times = times;
}
public void addObjects()
{
Random random = new Random();
for (int i = 0; i < objects; i++)
{
int randomx = random.nextInt(rows);
int randomy = random.nextInt(cols);
world[randomx][randomy] += SET;
}
}
}
setParameters()you need to update the size of world since rows and cols are not instantiated when you first declare world. In setParameters addworld = new int[rows][cols]; and change the initial declaration toint world[][];