So I wanna make an array outside a method so other methods can use it:
public int x = 0;
public int[] myIntArray = new int[x];
But the x is 0, and is later defined in a method as a number entered by user:
x = input.nextInt();
But the method has already size 0, so how would I modify (redefine) the array's size? I tried to do it by defining the array in a method, but if I do that, I cannot access the array from another method. I am a beginner and I can't do ArrayList, is it possible to do this?
EDIT: Basically: How do I define the size of an array later?
Sure, just declare it where you have it with public int[] myIntArray;
and then initialize it as soon as you know how big it has to be with myIntArray = new int[x];
You could declare it but not instantiate with public int[] myIntArray;
Later, after your code x = input.nextInt();
, instantiate the array with myIntArray = new int[x]
within that method. You should still be able to access the array from other methods
You can just declare it without initializing like:
public int[] myIntArray;
then put the value after you got one.
x = input.nextInt();
myIntArray = new int[x];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.