This week's book giveaway is in the JavaScript forum.
We're giving away four copies of JavaScript Promises Essentials and have Rami Sarieddine on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes declaring new variables within while loops Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "declaring new variables within while loops" Watch "declaring new variables within while loops" New topic

declaring new variables within while loops

Theresa Marlin
Ranch Hand

Joined: Sep 23, 2009
Posts: 49
I need to write a program that has user input for how many numbers will be inputted, and then inputs them all. I am having trouble figuring out how to declare new variables within a while loop.
For example,

How many numbers will you enter? 5

And then, within a while loop, I need to somehow declare five or however many separate variables, but I'm unsure how to do this.

Thanks for your help!
Henry Wong

Joined: Sep 28, 2004
Posts: 18965

Have you learned arrays yet?


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Max Rahder
Ranch Hand

Joined: Nov 06, 2000
Posts: 177
You can use an array or a collection to store a set of values. Collections are more flexible because they can grow and shrink as needed, whereas an array has a fixed size. In your case, if the user specifies that there are five elements, and you can do something like String[] values = new String[k]; (where k holds the user-specified number of elements). You'd assign values to the array using a statement like: values[i] = someUserSuppliedValue;. To store a bunch of strings in a collection you would do something like List<String> values = new ArrayList<String>();, then assign values to it using a statement like values.add(someUserSuppliedValue);

I hope that helps! :-)
Theresa Marlin
Ranch Hand

Joined: Sep 23, 2009
Posts: 49
Thank you both!
I agree. Here's the link:
subject: declaring new variables within while loops