When in.close () is used; of the Scanner class?

1

I am trying to compile the program to know if it is even or odd and I get an error "Resource leak: input never close", where it is recommended to close the Scanner?

package pares;

import java.util.Scanner;

public class Pares {


public static void main(String[] args) {

    int numero;
    Scanner input = new Scanner(System.in);

    System.out.println("introduzca un numero");
    numero = input.nextInt();

    if(esPar(numero)){
        System.out.println("el numero"+numero+"el numero es par." );
    } else {
        System.out.println("el numero"+numero+"el numero es impar.");
    }
} // if 
    public static boolean esPar( int numero){
      if( numero % 2 == 0 )
          return true;
      else{
          return false;
      }
    }



}
    
asked by Gerardo Bautista 16.05.2017 в 02:42
source

2 answers

4

What you must do is close the Scanner , which inside will close the resource System.in . If you use Java 7 or higher, you can use try-with-resources :

try (Scanner input = new Scanner(System.in)) {
    System.out.println("introduzca un numero");
    numero = input.nextInt();
    //resto del código del método main...
}

In case of using Java 6 or lower, you must call the Scanner#close method manually. The best way to do this is within a block try-finally :

Scanner input = null;
try {
    input = new Scanner(System.in)
    System.out.println("introduzca un numero");
    numero = input.nextInt();
    //resto del código del método main...
} catch (Exception e) {
    //manejar la excepción
} finally {
    if (input != null) {
        input.close();
    }
}
    
answered by 16.05.2017 / 02:45
source
2

Well I'm going to make you a ternary to perfect and you'll be a vice. So the exercise is faster.

import java.util.Scanner;

public class Pairs {

private static Scanner input;
private static boolean cerrarScanner;


public static void main(String[] args)
{

try
{

    input = new Scanner(System.in);

    System.out.println("Introduzca un número");
    int numero = input.nextInt();

    imprimir(numero);
}
catch (Exception e)
{
    // puedes manejar un log si quieres aunque para el ejercicio que es
    // igual es un poco mucho
}
finally
{
    cerrarScanner();
}
}


/**
 * @param numero
 */
public static void imprimir(int numero)
{

if(esPar(numero))
{
    System.out.println("El número " + numero + " el número es par.");
}
else
{
    System.out.println("El número " + numero + " el número es impar.");
}
}


public static boolean esPar(int numero)
{

// puedes usar un ternario si quieres
boolean esPar = (numero % 2 == 0) ? true : false;
return esPar;

}


public static void cerrarScanner()
{

cerrarScanner = (input != null) ? true : false;
input.close();

}

}

    
answered by 17.05.2017 в 11:28