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!
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.
You can create only one scanner object and use it any where else in this class.
Scanner is a class in java. util package used for obtaining the input of the primitive types like int, double, etc. and strings.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With