2

I currently have a project that is all in one class and has multiple methods. So far in each method I've had to use this line of code at the top to initialise my scanner. To take inputs from the user.

Scanner input = new Scanner(System.in);

My question is, is there a more efficient way of doing this?

Edit: By efficient I mean, decrease the amount of times I have to write this single line of code? Is there anyway I could initialise it once and re-use it?

user1861156
  • 169
  • 1
  • 2
  • 14
  • 4
    The homework tag is [deprecated](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated). And what do you mean by "more efficient"? Do you want to switch to another class, or use the Scanner more efficiently? Are you having problems with the way you're doing it now? – keyser Jan 22 '13 at 18:59
  • Use singleton pattern and factory method with Lazy initialization. – Shivam Jan 22 '13 at 19:04
  • To clarify little see http://stackoverflow.com/questions/5488072/reading-in-from-system-in-java – Mihai8 Jan 22 '13 at 19:05
  • 1
    @ShivamKalra Singletons are rarely an appropriate solution - and it clearly is not appropriate in that case. – assylias Jan 22 '13 at 19:05
  • 6
    Perhaps the problem is not knowing about object scope? Make the scanner a field of an object (that exact line of code will work), then input will be available in each method of that object. I can't really clarify further without a more specific question, and showing some existing code of what you've tried so far would go a long way. – Chuck Adams Jan 22 '13 at 19:06
  • 1
    @ShivamKalra Given that this seems like an entry-level assignment, chucking patterns and lazy initialisation at it seems like counterproductive pattern wank. You'd be replacing each of the `Scanner` instantiations with a call to `getScanner()`, and **adding** more code to implement that method. That's not really a simplification. – millimoose Jan 22 '13 at 19:18

2 Answers2

1

It will probably have a negligible impact on your performance, but if you're like me and want to do it the neurotically efficient way I would recommend making input a field of your class. This way it will enjoy class scope and be accessible to all of your methods. To ensure that it is always a valid scanner (never null), it should probably public static final:

class TheClass
{
    public static final Scanner input = new Scanner(System.in);

    public void someMethod()
    {
          String text = input.readLine();
    }

    ...
}
ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
0
Scanner input 

outside methods, and used by all of them ? maybe create it as static ?

in constructor you can put this code

input = new Scanner(System.in); 

or if you go static way you can add this code

static Scanner input;

static {
  input= new Scanner(System.in); 
 }

will this work in your case ?

not sure what exactly is your goal.