How to use the same Scanner across multiple classes in Java

混江龙づ霸主 提交于 2020-06-14 04:18:34

问题


I have a program that uses multiple classes, I want the other classes to be able to access the same scanner that I have declared in the main class, I assume it would be done using some sort of get method, however I am unable to find any resources to help me.

Here are the Scanners that I have made in my main class:

  Scanner in = new Scanner(System.in);
            System.out.println("Enter a filename");
            String filename = in.nextLine();
            File InputFile = new File (filename);
            Scanner reader = new Scanner(filename);

The reader Scanner is the one I want to be able to access across the other classes that make up the program, can anyone give me some guidance on how I can do this? Thanks a lot for any help!


回答1:


Simply use public static final Scanner in = new Scanner(System.in); in you main class. After that you can call it from anywhere by MainClassName.in.

Also, be careful with arguments you pass to Scanner. I guess you wanted to put InputFile into Scanner, rather than filename =)

File InputFile = new File (filename);
Scanner reader = new Scanner(filename);



回答2:


Answering your question about dependency injection: here's a rough idea of dependency injection (via constructor):

public void wire() {
    ...
    Scanner reader = new Scanner(filename);
    ClassA objectA = new ClassA(reader);
    ClassB objectB = new ClassB(reader);
    ...
}

class A (class B would have a similar constructor):

public class ClassA {

    private Scanner reader;

    public ClassA(Scanner reader) {
        this.reader = reader;
    }
    ...
}

So the idea is that you create and wire up your objects in wire() method.




回答3:


There are so called design patterns that help you to deal with such daily issues. They show up best practises.

You are looking for something like a Singleton, an instance of a class that is unique to your software echosystem.

For your example, you can do something like this:

public class MyScanner{
   private static MyScanner instance = new MyScanner();
   private MyScanner(){
       // init the scanner
   }

   //Get the only object available
   public static MyScanner getInstance(){
      return instance;
   }

   public void read(File f){
      // read your file
   }
}


来源:https://stackoverflow.com/questions/29323116/how-to-use-the-same-scanner-across-multiple-classes-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!