简体   繁体   English

Java - 稍后定义数组大小

[英]Java - Define array size later

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 是 0,后来在一个方法中定义为用户输入的数字:

x = input.nextInt();

But the method has already size 0, so how would I modify (redefine) the array's size?但是该方法的大小已经为 0,那么我将如何修改(重新定义)数组的大小? 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?我是初学者,我不会做 ArrayList,可以这样做吗?

EDIT: Basically: How do I define the size of an array later?编辑:基本上:以后如何定义数组的大小?

Sure, just declare it where you have it with public int[] myIntArray;当然,只要用public int[] myIntArray;声明它在你有它的public int[] myIntArray; and then initialize it as soon as you know how big it has to be with myIntArray = new int[x];然后一旦你知道它有多大就用myIntArray = new int[x];初始化它myIntArray = new int[x];

You could declare it but not instantiate with public int[] myIntArray;你可以声明它但不能用public int[] myIntArray;实例化它public int[] myIntArray;

Later, after your code x = input.nextInt();稍后,在您的代码x = input.nextInt(); , instantiate the array with myIntArray = new int[x] within that method. ,在该方法中使用myIntArray = new int[x]实例化数组。 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM