954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Please help on updating instance variable

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();
}
Monyet
Light Poster
29 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

What do you mean?

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

nvm i just got it again -.-"

Monyet
Light Poster
29 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

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

Monyet
Light Poster
29 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

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

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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

Monyet
Light Poster
29 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

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

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

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.

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 

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?

masijade
Industrious Poster
Moderator
4,253 posts since Feb 2006
Reputation Points: 1,471
Solved Threads: 494
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You