1

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?

4
  • 1
    You could pass reference to classes, use a static field.. Commented Feb 19, 2014 at 17:31
  • Or you could not pipe system.in into the scanner at all. Just pass the input to the Scanner as a String. Commented Feb 19, 2014 at 17:32
  • Why are you closing the Scanners anyway, knowing that it closes the standard input? Commented Feb 19, 2014 at 17:45
  • I thought it was just good practice to close all the resources you use? Commented Feb 19, 2014 at 21:12

2 Answers 2

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.