This is my code, I'm thinking to update the instance variable m, so that I can update my array1[m].. does anyone have suggestion? please help thank you

private int m;
private int n;
private int array1[] = new int[m];
private int array2[][] = new int[m][n];
public int Init()
{
Scanner input = new Scanner(System.in);
Random r = new Random();
do
{
System.out.print("Enter m for array1 [10, 100]: ");
m = input.nextInt();
if (m < 10 || m > 100)
System.out.println("Error: please try again");
}
while (m < 10 || m > 100);
System.out.println();
System.out.println("Initial Array Elements");
for (int i = 0; i < array1.length; i++)
{
array1[i] = r.nextInt(101) + 10;
System.out.printf("%d ", array1[i]);
}
System.out.println();
}
Member Avatar for iamthwee

What do you mean?

nvm i just got it again -.-"

i forgot that there are 2 initialization array methods...

int array[];
array = new int[m];

and

int array[] = new int[m]

I usually use the second method, which makes me forgot that I can use the first method too :D

the code you posted won't even compile, as m and n aren't initialised yet at the time you first use them.

it's actually compiled, java initialize m and n as 0

yah, misread it. Looked like you had them defined inside a method, in which case it wouldn't have compiled.

You're problem isn't, however, in updating the instance variable. m and n are getting updated just fine, with what you are doing. What is not working, is that the array is not dynamically changing size along with those variables. That is not the way it works. You need to redefine the array to get it to change its size.

Also, what is this line?

while (m < 10 || m > 100);

You do realize that this while statement will hang forever if m is less than 10 or greater than 100, right?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.