This is my program in which I am facing resource leak issue:
import java.util.*;
public class MarksSheetForLoop {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int input = 1;
// using for loop
System.out.println `your text`("Using for loop");
for (; input == 1;) {
System.out.print (" Enter Marks = " );
int marks = sc.nextInt();
// grade
if (marks >= 90 && marks <= 100) {
System.out.println (" GOOD ");
} else if (marks >= 60 && marks <= 89) {
System.out.println("ALSO GOOD");
} else if (marks >= 0 && marks <= 59) {
System.out.println("GOOD AS WELL");
} else {
System.out.println("INVALID MARKS");
}
// continue
System.out.println("Want to continue? 1[YES] or 2[NO]");
input = sc.nextInt();
}
if (input == 2) {
System.out.println("For Loop End");
} else {
System.out.print("Invalid Input");
}
// using do-while loop
System.out.println("Do-While Loop");
do {
System.out.print("Enter Marks= ");
int marks = sc.nextInt();
// grade
if (marks >= 90 && marks <= 100) {
System.out.println("GOOD");
} else if (marks >= 60 && marks <= 89) {
System.out.println("ALSO GOOD");
} else if (marks >= 0 && marks <= 59) {
System.out.println("GOOD AS WELL");
} else {
System.out.println("INVALID MARKS");
}
// continue
System.out.println("Want to continue? 1[YES] or 2[NO]");
input = sc.nextInt();
} while (input == 1);
if (input == 2) {
System.out.println("Do-While Loop End");
} else {
System.out.println("INVALID INPUT");
}
// using while loop
System.out.println("Using While Loop");
input = 1;
while (input == 1) {
System.out.print("Enter Marks= ");
int marks = sc.nextInt();
// grade
if (marks >= 90 && marks <= 100) {
System.out.println("GOOD");
} else if (marks >= 60 && marks <= 89) {
System.out.println("ALSO GOOD");
} else if (marks >= 0 && marks <= 59) {
System.out.println("GOOD AS WELL");
} else {
System.out.println("INVALID MARKS");
}
// continue
System.out.println("Want to continue? 1[YES] or 0[NO]");
input = sc.nextInt();
}
sc.close();
if (input == 0) {
System.out.println("END");
} else {
System.out.println("INVALID INPUT");
}
sc.close();
}
}
I was practicing the loops but compiler is showing a resource leak even after closing the scanner. Although I closed the scanner but I don’t understand where should I close it. Should I open and close it multiple times, as in , in every loop or is only once enough?
New contributor
Fadeela is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.