Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the same Scanner across multiple classes in Java

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!

like image 539
Samolivercz Avatar asked Mar 28 '15 22:03

Samolivercz


People also ask

Can you reuse the same Scanner Java?

Add all the parameters that you want to pass to scan() in an array and using a for loop pass them all to scan() while when returning, adding them again in their respective array position so then you can easily reuse them wherever you want. Save this answer.

Can I have multiple scanners in Java?

You can create only one scanner object and use it any where else in this class.

What does Scanner SCNR do in Java?

Scanner is a class in java. util package used for obtaining the input of the primitive types like int, double, etc. and strings.


2 Answers

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);
like image 153
ar4ers Avatar answered Sep 19 '22 13:09

ar4ers


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.

like image 42
Sergey Pauk Avatar answered Sep 21 '22 13:09

Sergey Pauk