Use of scanner class in methods
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();
}
...
}
user1861156
Updated on June 04, 2022Comments
-
user1861156 almost 2 years
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?
-
keyser over 11 yearsThe homework tag is 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?
-
Shivam over 11 yearsUse singleton pattern and factory method with Lazy initialization.
-
Mihai8 over 11 yearsTo clarify little see stackoverflow.com/questions/5488072/…
-
assylias over 11 years@ShivamKalra Singletons are rarely an appropriate solution - and it clearly is not appropriate in that case.
-
Chuck Adams over 11 yearsPerhaps 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.
-
Montre over 11 years@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 togetScanner()
, and adding more code to implement that method. That's not really a simplification.
-