简体   繁体   中英

Array input without pre-defining array size

I want user input of an array of integers without explicitly mentioning the array-size. It should be just like command line arguments, ie if we want to access the length of the string array (String args[]) we use "args.length", we can also perform other string array functions on it.

We always first ask the user the number of inputs he'd give and then ask for the inputs. But I directly want to ask for the array element inputs. What I have already tried is: I asked for the input and instructed the user to enter a special character...let's say full stop "." after he is done enter the elements of array. Then I used conditional statements to check id he entered "." and stopped taking user input. Thus I had an array, but I always had to make the user enter "." to terminate the process of taking inputs.

You could use an ArrayList for this, add to it the elements/inputs, and then (if needed) convert the list to an array using the toArray() method:

ArrayList<String> list = new ArrayList<>();
list.add("input1");
list.add("input2");
list.add("input3");

And to get the length of the list, use list.size()

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.

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