'I am not able to get the output for the following code and the error is shown in 'sc'. Error shown is "Resource leak: 'sc' is never closed"

I am trying to take input from the keyboard but I am getting errors.

 import java.util.*;
        public class FirstClass{
            public static void main(String[] args){
                Scanner sc=new Scanner(System.in);
                String name=sc.next();
                System.out.println(name);
           }


}


Solution 1:[1]

I copy pasted your code in a text editor inside a file called FirstClass.java

Compiled your code using javac FirstClass.java Ran it using java FirstClass

This takes the cursor to the next line where an input is expected. I entered the string "hey", and your code printed out "hey".

In short, your code is working fine. You need to enter an input after you run your code.

PS: 'sc' is never closed is a warning and not an error. You should however consider using try-with-resources to prevent any resource leaks.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Satyarth Shankar