有什么方法可以在其他类中使用Scanner对象? [英] Is there any way I can use a Scanner object in a different class?
问题描述
所以我有一个简单的Scanner对象:
So I have a simple Scanner object:
Scanner scan = new Scanner (System.in);
我正在尝试在其他类中声明的方法中使用此Scanner对象.无论如何,这可以做到吗?我也尝试过使用:
I am trying to use this Scanner object inside a method that I have declared in a different class. Is there anyway this can be done? I have also tried using:
public static final Scanner scan = new Scanner(System.in);
但这并没有真正的帮助
推荐答案
public static final Scanner scan = new Scanner(System.in);
正如您将Scanner
实例声明为public
和static
一样.因此,您可以使用类"引用进行访问.
As you have declared Scanner
instance as public
and static
. So you access it using the Class reference.
另一个类中的代码.
String intpu = ClassName.scan.next();
ClassName
是定义它的类的名称.
ClassName
is the name of the class in which it is defined.
还有其他方法可以实现这一目标:
There could be other ways of achieving this:
-
将此传递到要使用它的另一个类的方法.
Pass this to method of the other class where you want to use it.
如果将Scanner
实例定义为该类的成员,则创建该类的实例并使用getter方法对其进行访问.
If you define Scanner
instance as member of the class, then create the instance of class and access it using the getter method.
您可以在另一个类中创建Scanner
的新实例.
You can create a fresh instance of the Scanner
in the other class.
这篇关于有什么方法可以在其他类中使用Scanner对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!