This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Counting inputs and scanner class

 
James Farber
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you count the amount of inputs using the Scanner class?
Say for instance I want the user to enter an even, and only an even amount of numbers

"Enter an even amount of numbers :"

5 12 7 2

after hitting return, how can I store these into one variable?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For a problem like this, I recommend you start with a smaller problem and then build on your solution For example:

1. Write a program that reads just one number from the list using a Scanner and prints it out.

2. Add a loop to make the Scanner read repeatedly. Is there a way to make the Scanner stop once there are no more numbers to read?

3. Add an int variable "count". Every time you go through the loop, add one to the count. After you're done with the loop, print the count.

If you get stuck on one part, show us what you've done so far and we can offer more suggestions.
 
K. Tsang
Bartender
Posts: 3502
14
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This looks harder than it sounds!! Yet I see there are many ways to do it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic