java 在方法中使用扫描器类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14465976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of scanner class in methods
提问by user1861156
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?
编辑:高效我的意思是,减少我必须编写这行代码的次数?无论如何我可以将它初始化一次并重新使用它吗?
采纳答案by ApproachingDarknessFish
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
:
它可能对你的表现产生的影响可以忽略不计,但如果你像我一样并且想要以神经质的有效方式做到这一点,我建议input
你在课堂上设置一个领域。通过这种方式,它将享受类范围并且可以访问您的所有方法。为了确保它始终是一个有效的扫描器(从不为空),它可能应该public static final
:
class TheClass
{
public static final Scanner input = new Scanner(System.in);
public void someMethod()
{
String text = input.readLine();
}
...
}
回答by Puppet Master 3010
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.
不知道你的目标到底是什么。