有什么方法可以在其他类中使用Scanner对象? [英] Is there any way I can use a Scanner object in a different class?

查看:102
本文介绍了有什么方法可以在其他类中使用Scanner对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个简单的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实例声明为publicstatic一样.因此,您可以使用类"引用进行访问.

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:

  1. 将此传递到要使用它的另一个类的方法.

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆