I'm asking the user to enter some numbers between 1 and 100 and assign them into an array. The array size is not initialized since it is dependent on the number of times the user enters a number.
How should I assign the array length?
If user enters 5 6 7 8 9 (5 numbers), then
int[] list;
becomes
int[] list = new int[5];
I'm trying 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);
You can declare an array without a size specifier for the leftmost dimension in multiples cases: as a global variable with extern class storage (the array is defined elsewhere), as a function parameter: int main(int argc, char *argv[]) . In this case the size specified for the leftmost dimension is ignored anyway.
Answer: No. It is not possible to declare an array without specifying the size. If at all you want to do that, then you can use ArrayList which is dynamic in nature. Q #2) Is Array size fixed in Java?
Read the entire line using sc. nextLine() and then split() using \\s+ . This way, you don't have to worry about size of input (number of elements). Use Integer.
You should use a List
for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List
instead. Most would probably tackle this problem by using an ArrayList
.
If you really can't use a List
, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList
does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList
.
I think you need use List or classes based on that.
For instance,
ArrayList<Integer> integers = new ArrayList<Integer>();
int j;
do{
integers.add(int.nextInt());
j++;
}while( (integers.get(j-1) >= 1) || (integers.get(j-1) <= 100) );
You could read this article for getting more information about how to use that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With