Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to close the scanner used more then once in the class

As i know its better practice to have as less code duplication as possible, So i decided to declare only one scanner throughout the class, but where shall I close the scanner object or is it not necessarily to close it, what does closing the scanner do.

  private Scanner scanner;
/**
 * Constructor for objects of class Scanner
 */
public Ssss()
{
    // initialise instance variables
     scanner = new Scanner(System.in);
}
public void enterYourName()
{
    System.out.println("Enter your Name");
    String name = scanner.nextLine();
    System.out.println("Your name is:" + name);
}
public void enterYourAge()
{
    System.out.println("Enter your Age");
    int age = scanner.nextInt();
        System.out.println("Your age is: " + age);
}
like image 273
mohamed ghassar Avatar asked Oct 03 '22 14:10

mohamed ghassar


1 Answers

Assuming this code is in a class Ssss (as it appears), consider:

  1. Your class contains and uses a Scanner object, so it is responsible for closing it.
  2. The Scanner represents an internal resource, and state of your class... different methods will refer to it at different times.
  3. You cannot know when the user of your class (the main program?) is done with it, so you cannot unilaterally close the Scanner -- where would you close it?

The solution is that your class Ssss must provide its own method that allows the code using Ssss to say "I'm done with you". This method is traditionally called close(), and in it you would close the Scanner (and clean up any other resources).

The client (calling class) must wrap usage of your class Ssss in a try-finally block and call your close() method in the finally clause.

If you are using Java7, your class Ssss should implement AutoCloseable so it can be used in a try-with-resources statement to take advantage of that Java7 feature.

like image 139
Jim Garrison Avatar answered Oct 13 '22 11:10

Jim Garrison