• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Reusing scanner

 
Ranch Hand
Posts: 56
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When using the scanner from system.in I can't reuse it. Say I want the user to give multiple input, do I really have to initialize a new scanner each time?
Example:


Now when I press 1 to book a ticket that's the result:

As you can see the scanner takes the right menuchoice and executes the right switch case, but instead of waiting for the name of the users it asks for the type right away.
Is there a way to prevent that without initializing a new scanner?
 
Saloon Keeper
Posts: 5533
213
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Pieter,

if you have:

then if you type say 1, followed by an enter, then java reads that 1, but leaves a 'newline' in the scanners buffer. So the moment you do:

then that pending newline is appointed to the variable 'name', and java goes on.

You can see this effect in lines 12-17.
A simple remedy is to put 'scanner.nextLine();' between lines 12 and 13, that will swallow that newline.

People here will show you some handy input-routines that will make life easy on you.
 
Marshal
Posts: 79703
381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is best to use a single Scanner object reading System.in for the whole application. The best way to do that is to crete a utility class reading inputs; if you search my posts for, “Scanner utility class,” you will eventually find such a utility class. I insist you acknowledge its source if you use it. It is better to understand the concepts behind it and write your own. I haven't managed to make such code thread‑safe.

But you won't find the whole class all in one place There is a serious mistake in one of my posts.
 
Check your pockets for water buffalo. You might need to use this tiny ad until locate a water buffalo:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic