Hello good, I have the following code although it could perfectly be any other code since it happens to me with all those who use the Scanner
package ejercicios.Obligatoria2;
import java.util.Scanner;
public class PROG02_EJER4{
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
int intro;
System.out.println("introduce tu edad a continuacion");
intro = sc.nextInt();
while (intro < 18){
System.out.println("Es menor de edad");
break;
}
while (intro >18){
System.out.println("Es mayor de edad");
break;
}
}
}
The problem I have is that at this point:
Scanner sc = new Scanner(System.in);
The "sc" in the visual studio code and in other IDEs outlines it in yellow and tells me that to solve it I circle the "try" code, that is, according to visual studio it would look like this:
package ejercicios.Obligatoria2;
import java.util.Scanner;
public class PROG02_EJER4{
public static void main(String[]args) {
try (Scanner sc = new Scanner(System.in)) {
int intro;
System.out.println("introduce tu edad a continuacion");
intro = sc.nextInt();
while (intro < 18){
System.out.println("Es menor de edad");
break;
}
while (intro >18){
System.out.println("Es mayor de edad");
break;
}
}
}
}
Could someone tell me why this happens and why visual studio solves it with "try" since I don't know exactly what the try is for and how and at what points it is used Thanks
PS: I know that if I put an if to make the condition of:
while (intro < 18){
System.out.println("Es menor de edad");
break;
}
while (intro >18){
System.out.println("Es mayor de edad");
break;
I would be cleaner but the exercise I have is to do it without the if
It marks it in yellow because you are having a resource leak, that is, you are not closing the scanner. To fix it you should use the .close() method .
The IDE is solving it for you with a try, specifically, the type of try that it is recommending is called try-with-resources . What it does is automatically close the resource declared inside the parentheses. In this way, you avoid writing the .close() when you finish using your resource, since it is inferred that once the code inside the try block finishes executing, it will close automatically.