Java 如何将扫描仪对象设为静态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25916476/
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
how to make scanner object as static
提问by Tethys0
how can i refer to Scanner object which is defined globally from a static method(say main() ).. That is, how to make Scanner object as static.
我如何引用从静态方法(比如 main() )全局定义的 Scanner 对象。也就是说,如何将 Scanner 对象设为静态。
Program (# for reference to my problem) :
程序(# 参考我的问题):
import java.util.Scanner;
class spidy {
Scanner input = new Scanner(System.in); /*DECLARING SCANNER OBJECT OUTSIDE MAIN METHOD i.e Static method */
public static void main(String args[]) {
System.out.println("Enter a number");
int n = input.nextInt();
}
}
Error: non static variable input cannot be referenced from the static content
错误:不能从静态内容中引用非静态变量输入
采纳答案by adityaekawade
I had faced a similar doubt while solving a problem on Static Initializer Block. And there is a simple solution to it.
在解决静态初始化程序块的问题时,我也遇到过类似的疑问。并且有一个简单的解决方案。
Write as:
写成:
static Scanner input = new Scanner(System.in);
Instead of :
代替 :
Scanner input = new Scanner(System.in);
回答by Elliott Frisch
If I understand your question, then you could change this
如果我理解你的问题,那么你可以改变这个
Scanner input = new Scanner(System.in);
to (visible to all other classes - you said global)
to(对所有其他类可见 - 你说的是global)
public static Scanner input = new Scanner(System.in);
or (visible to the current class - any other static method (main()
in your case) )
或(对当前类可见 - 任何其他静态方法(main()
在您的情况下))
private static Scanner input = new Scanner(System.in);
回答by Suthan Srinivasan
Just use static
keyword before Scanner
class.
只需static
在Scanner
上课前使用关键字。
Example:
例子:
static Scanner scan=new Scanner(System.in);
By using the scan object we refer anywhere in the code
通过使用 scan 对象,我们可以在代码中的任何地方引用