• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
Sheriffs:
  • Devaka Cooray
  • paul wheaton
  • Mark Herschberg
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Frits Walraven
  • Jj Roberts
Bartenders:
  • Carey Brown
  • salvin francis
  • Piet Souris

How to declare "Scanner"

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi developers,

is it okay to declare the "Scanner" before the main method?



I want it to be useable in every method in my program without the need of having to create it in every method again.
Is this the way to go or is there a better solution?

Thanks in advance and best regards,
Jens
 
Marshal
Posts: 72059
312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, that will work. Much better than re‑declaring it. I would declare it in a different class and make it final, because, as you correctly said, you only need one Scanner per (single‑threaded) application. Once initialised, it never needs to be re‑assigned.I think there is a better way to get keyboard input, but you will have to devote a few hours' work to it. I have written myself a utility class. Search my posts for “utility class Scanner” and you will find it, but only in pieces which you will have to assemble. I can write...and it is so written that the problem about getting an empty line from nextLine() doesn't occur. If you use that class in any code you are giving to anybody else, please acknowledge its course in its first comment.
 
Saloon Keeper
Posts: 12723
277
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jens Jensen wrote:Is this the way to go or is there a better solution?


Inject the Scanner into the constructors of the classes that need it.

I can't imagine there are many classes that need user input. If there are, you probably need to redesign your application.
 
Jens Jensen
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks all for your input!
Appreciate it.

Best regards,
Jens
 
Your mother is a hamster and your father smells of tiny ads!
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic