-2

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?

David Koplik
  • 21
  • 1
  • 1
  • 7
  • 1
    why not use arraylist instead? You can convert this list to an array later if you want as array only at later stage. – Raman Shrivastava Apr 17 '16 at 18:45
  • Possible duplicate of [Resize an Array while keeping current elements in Java?](http://stackoverflow.com/questions/13197702/resize-an-array-while-keeping-current-elements-in-java) – paisanco Apr 17 '16 at 18:47
  • 1
    So declare the array _after_ the user has entered its size. – Tunaki Apr 17 '16 at 18:47

3 Answers3

2

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];

Vampire
  • 35,631
  • 4
  • 76
  • 102
0

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

Michael
  • 776
  • 4
  • 19
0

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];