简体   繁体   English

有什么办法可以在不同的类中使用 Scanner 对象吗?

[英]Is there any way I can use a Scanner object in a different class?

So I have a simple Scanner object:所以我有一个简单的 Scanner 对象:

Scanner scan = new Scanner (System.in);

I am trying to use this Scanner object inside a method that I have declared in a different class.我试图在我在另一个类中声明的方法中使用这个 Scanner 对象。 Is there anyway this can be done?无论如何这可以做到吗? I have also tried using:我也尝试过使用:

public static final Scanner scan = new Scanner(System.in);

but this didn't really help但这并没有真正帮助

public static final Scanner scan = new Scanner(System.in);

As you have declared Scanner instance as public and static .正如您已将Scanner实例声明为publicstatic So you access it using the Class reference.因此,您可以使用类引用来访问它。

Code in the other class.其他类中的代码。

String intpu = ClassName.scan.next();

ClassName is the name of the class in which it is defined. ClassName是定义它的类的名称。

There could be other ways of achieving this:可能还有其他方法可以实现这一点:

  1. Pass this to method of the other class where you want to use it.将其传递给您要使用它的其他类的方法。

  2. If you define Scanner instance as member of the class, then create the instance of class and access it using the getter method.如果将Scanner实例定义为类的成员,则创建类的实例并使用 getter 方法访问它。

  3. You can create a fresh instance of the Scanner in the other class.您可以在其他类中创建Scanner的新实例。

A common design pattern to address this is dependency injection.解决这个问题的常见设计模式是依赖注入。 One form of dependency injection is called constructor injection.依赖注入的一种形式称为构造函数注入。 For this, create a constructor which accepts the object the class depends on.为此,创建一个接受类所依赖的对象的构造函数。 Then when you instantiate that class, you pass in the object you would like it to operate on (in your case your scanner).然后当你实例化那个类时,你传入你希望它操作的对象(在你的例子中是你的扫描仪)。

Example例子

Main - Caller class: Main - 调用者类:

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        AnotherReader anotherReader = new AnotherReader(scan);
        anotherReader.readSomething();
    }
}

AnotherReader - class which requires a Scanner dependency: AnotherReader - 需要Scanner依赖的类:

public class AnotherReader {           

    Scanner scan;                      

    public AnotherReader(Scanner scan) 
        this.scan = scan;              
    }                                  

    public void readSomething(){       
        String line = scan.nextLine(); 
        // Do something                

    }                                  
}                                      

You can pass the Scanner object's reference to that Method in the call.您可以在调用中将 Scanner 对象的引用传递给该方法。 something like method(Scanner sc)method(Scanner sc)

You could try inheritance : Super Class:您可以尝试inheritance :超类:

public class superclass
{
     Scanner scan=new Scanner(System.in); 
     //scanner object declared globally
     //constructor
     //other methods etc.
}

Sub Class:子类:

public class subclass extends superclass
{
//the scanner object can be inherited
}

Using inheritance,the subclass can inherit the scanner object in the super class.使用继承,子类可以继承超类中的扫描仪对象。 I hope this works.Please let me know if something goes wrong.我希望这有效。如果出现问题,请告诉我。

Can also be done without inheritance(without extending):也可以在没有继承的情况下完成(不扩展):

  • Simply create the object of superclass in the concerned subclass method as:只需在相关的子类方法中创建超类的对象,如下所示:

     superclass ob=new superclass(); //created superclass object String takeIN= ob.scan.next(); /*refers to scanner object in superclass because scanner object is declared a field(global object) in superclass.*/
  • Following your example,if the scanner object in superclass is made static,you can simply use it like:按照你的例子,如果超类中的扫描仪对象是静态的,你可以像这样简单地使用它:

     Scanner takeIn=superclass.scan.next();

My way of solving this problem is to add a Scanner parameter to the method I am calling of the class that needs to use the Scanner, and then pass the scanner variable as an argument when calling the method.我解决这个问题的方法是在我调用的需要使用Scanner的类的方法中添加一个Scanner参数,然后在调用该方法时将scanner变量作为参数传递。

My main method:我的主要方法:

import java.util.Scanner;

public class ScannerTest
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        CalledClass cC = new CalledClass();

        cC.testMethod(input);
    }
}

CalledClass.java:调用类.java:

import java.util.Scanner;

public class CalledClass
{
    public void testMethod(Scanner x)
    {
        System.out.println("Enter anything");
        String myString = x.next();
        System.out.println(myString);
    }

}

It's not the prettiest thing, but it works.这不是最漂亮的东西,但它确实有效。

Here is how I do it:这是我的操作方法:

  1. Create MyScanner.java in a new package (in this case: mypackage)在新包中创建 MyScanner.java(在本例中为:mypackage)

     package mypackage; import java.util.Scanner; public class MyScanner { static Scanner scan = new Scanner(System.in); public static String scan() { return scan.next(); } public static String scanLine() { return scan.nextLine(); } public static int scanInt() { return scan.nextInt(); } }
  2. Use it anywhere by (static) importing all methods from MyScanner class of mypackage.通过(静态)从 mypackage 的 MyScanner 类导入所有方法,在任何地方使用它。

     package yourpackage; import static mypackage.MyScanner.*; public class Main { public static void main(String[] args) { System.out.print("put an integer: "); int a = scanInt(); System.out.println("int a = " + a); } }

If you don't want to use static import, change import static mypackage.MyScanner.*;如果您不想使用静态导入,请更改import static mypackage.MyScanner.*; in MyScanner.java to import mypackage.MyScanner;在 MyScanner.java 中import mypackage.MyScanner; . . By doing this, you cannot call your scanner methods directly anymore, you need to specify the class containing the methods.通过这样做,您不能再直接调用您的扫描器方法,您需要指定包含这些方法的类。 For example: MyScanner.scanInt() , MyScanner.scan() .例如: MyScanner.scanInt()MyScanner.scan()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有什么办法可以创建/获取并返回课程 <T<?, ?> &gt;对象? - Is there any way I can create/get and return a Class<T<?, ?>> object? 无法使用Scanner类 - Can't use the Scanner class 我可以在 Java 中使用 lambda 表达式的扫描仪(一类)吗? [等候接听] - Can I use Scanner(a class) using lambda expresion in Java? [on hold] 我可以在Java的整个类中使用一个Scanner变量吗? - Can i use one Scanner variable for a whole class in java? 我可以在文本文件中使用Scanner类获取信息吗? - Can I use Scanner class in text file for getting information? 有没有办法可以使用该类的现有实例(对象) - Is there a way i can use the existing instance (object) of the class 有什么方法可以输入类 Date 的日期,然后在其他类中将其用作整数? - Is there any way i can input a Date of class Date and then use it in other class as an integer? 有没有办法在Android上使用Android提供的类,如果没有,则使用另一种方法? - Any way to use an Android-provided class if on Android, and a different one if not? 如何使用在Scanner类的另一个类中创建的方法为该方法提供数据? - How can I use a method I created in another class with Scanner class to provide data to that method? 有没有办法可以检查 ArrayList 中的任何对象是否具有特定 class 的 object? - Is there a way I can check if any of the objects in an ArrayList have an object of a specific class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM