This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

declaring new variables within while loops

 
Theresa Marlin
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21000
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you learned arrays yet?

Henry
 
Max Rahder
Ranch Hand
Posts: 177
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both!
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic