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.

5
  • 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 Commented Aug 30, 2019 at 13:14
  • And... what is your question? Commented Aug 30, 2019 at 13:14
  • 4
    I suggest to use ArrayList or LinkedList Commented Aug 30, 2019 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. Commented Aug 30, 2019 at 13:18
  • Arrays are fixed-length. You cannot have a dynamic-length array. Commented Aug 30, 2019 at 13:19

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.