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 is it advisable 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;
}
}
}
What you should do is close the
Scanner
, which inside will close the resourceSystem.in
. If you're using Java 7 or higher, you can use thetry-with-resources
:In case of using Java 6 or lower, you must call the method
Scanner#close
manually. The best way to do this is inside a blocktry-finally
:Well I shoot to make you some ternaries to perfect and that you stay addicted. So the exercise is faster.
import java.util.Scanner;
public class Pairs {
}