Java: if you don’t know how to initialize the array size?

I asked the user to enter numbers between 1 and 100 and assign them to the array The array size is not initialized because it depends on the number of times the user enters a number

int[] list;

change

int[] list = new int[5];

I try to use a loop, but it won't stop

int[] integers;
int j = 0;
do {
       integers = new int[j + 1];
       integers[j] = in.nextInt(); 
       j++;      
} while((integers[j-1] >= 1) ||(integers[j-1]) <= 100);

Solution

You should use something like list instead of array As a general rule of thumb, use list instead when you don't know the number of elements to add to the array before hand Most people may solve this problem by using ArrayList

If you really can't use the list, you may have to use some initial size (maybe 10?) And track your array capacity instead of how many elements are added, and copy the elements to a new larger array if you run out (this is essentially done internally by ArrayList) Also note that in the real world, you'll never do this - you'll use one of the standard classes made specifically for such cases, such as ArrayList

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>