aspose file tools*
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "declaring new variables within while loops" Watch "declaring new variables within while loops" New topic
Author

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
author
Sheriff

Joined: Sep 28, 2004
Posts: 18829
    
  40

Have you learned arrays yet?

Henry


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: http://aspose.com/file-tools
 
subject: declaring new variables within while loops