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);
}
Assuming this code is in a class Ssss
(as it appears), consider:
Scanner
object, so it is responsible for closing it.Scanner
represents an internal resource, and state of your class... different methods will refer to it at different times.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.
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