If you do not close the java.util.Scanner object after reading data, you can get an warning saying "Resource leak: 'scanner' is never closed".
In the code below see that the Scanner object is closed in a finally block after reading all inputs using the Scanner object.
int number1, number2;
Scanner scanner = new Scanner(System.in);
try
{
System.out.println("Ener the first number");
number1 = scanner.nextInt();
System.out.println("Ener the second number");
number2 = scanner.nextInt();
}
finally
{
scanner.close();
}
In the code below see that the Scanner object is closed in a finally block after reading all inputs using the Scanner object.
int number1, number2;
Scanner scanner = new Scanner(System.in);
try
{
System.out.println("Ener the first number");
number1 = scanner.nextInt();
System.out.println("Ener the second number");
number2 = scanner.nextInt();
}
finally
{
scanner.close();
}
thanks. helped.
ReplyDeletecan you please explain what scanner.close(); actually does?
ReplyDeleteYou can read at http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()
DeleteThis comment has been removed by the author.
ReplyDeleteint number1, number2;
ReplyDeleteScanner scanner = new Scanner(System.in);
try
{
System.out.println("Ener the first number");
number1 = scanner.nextInt();
System.out.println("Ener the second number");
number2 = scanner.nextInt();
}
finally
{
scanner.close();
}
http://tehapps.com/