0

I am trying to print the contents of an array. For example I have defined an int array of size 10. But the user entered only 8 numbers. So the last two positions in an array have an value of zero. When I am printing the array I get all ten positions. Is it possible to print only up till the user entered.Also the user decides how many to enter so I cannot hard code the position for printing the array. Thanks.

1
  • Please enter the code you have done so far so someone can help with your question Commented Oct 3, 2015 at 2:24

2 Answers 2

1

Is it possible to print only up till the user entered.

Yes, keep track of how many items the user entered. This can be done with a separate int counter variable that you increment as the user enters an item, or if you want, you can fill the array with values that the user would never enter, for example, Integer.MIN_VALUE, and then display results up until you reach the non-sense values. The danger here is, what happens if the user just happens to pick that non-sense value? That's why I'd go with the first suggestion.

Also the user decides how many to enter so I cannot hard code the position for printing the array.

Yep, just as I said above.

Edit: or best of all, just do what Patricia Shanahan says.

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

Comments

1

If you have to use an array, keep track of the number of valid elements as suggested by Hovercraft Full Of Eels' answer.

If you have the option, it may be cleaner to use an ArrayList, which grows as you add elements. That way, at the end of input it will have exactly the right size, and you can print the whole of it.

1 Comment

To Sesha, yep, this way is better overall as it's much cleaner, and you don't have to artificially limit the number of entries as you do with a fixed size array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.