user1861156
user1861156

Reputation: 169

Use of scanner class in methods

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?

Upvotes: 2

Views: 18325

Answers (2)

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14323

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();
    }

    ...
}

Upvotes: 1

Puppet Master 3010
Puppet Master 3010

Reputation: 261

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.

Upvotes: 0

Related Questions