0

I want user input of an array of integers without explicitly mentioning the array-size. It should be just like command line arguments, i.e. 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.

  • 1
    can you provide your code, it would be much more easy to help you with part of the code and not all of it since this isn't a "do my job/homework" website – Daniel_Kamel Aug 30 '19 at 13:14
  • And... what is your question? – JB Nizet Aug 30 '19 at 13:14
  • 4
    I suggest to use `ArrayList` or `LinkedList` – yascho Aug 30 '19 at 13:14
  • 1
    If the number of inputs is not fixed, you need some way to tell the program the input has ended. `.` is one way, others are an empty string, i.e. the user press enter/return without entering anything. Ctrl-d is also commonly used to end input, but it could be difficult if you are using a `Scanner`. – Roger Gustavsson Aug 30 '19 at 13:18
  • Arrays are fixed-length. [You cannot have a dynamic-length array](https://stackoverflow.com/a/1647277/5699679). – Avi Aug 30 '19 at 13:19

1 Answers1

1

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()

Anis R.
  • 6,656
  • 2
  • 15
  • 37