Birdfriender
Birdfriender

Reputation: 393

Using a scanner across multiple classes in Java?

I have a program in Java that needs to get user input from the console at multiple points across multiple classes. I tried using a scanner in each class but when I close one scanner it closes system.in so I want to use the same scanner across the whole program. I open the scanner in the main class but how do I use the same scanner in other classes?

Upvotes: 1

Views: 4202

Answers (2)

Aaron Srun
Aaron Srun

Reputation: 1

import java.util.Scanner;

public class ScannerSaver 
{
    private Scanner scan;

    public ScannerSaver(Scanner s)
    {
        this.scan = s;
    }
}

Simply pass the scanner in as a parameter.

Upvotes: 0

Wasif Hossain
Wasif Hossain

Reputation: 3950

You have to inject the scanner instance to other classes through constructor. Like below:

import java.util.*;

public class Test1
{
    private Scanner _scanner;

    public Test1(Scanner sc)
    {
        _scanner = sc;
    }
}

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        Test1 testObj = new Test1(sc);
    }
}

Upvotes: 2

Related Questions