+ 2

Scanner variable error in Eclipse

Eclipse is forcing me to declare the Scanner Variable like this "private static Scanner s;" Why is that? import java.util.Scanner; public class myclass{ private static Scanner s; public static void main(String[] args) { s = new Scanner(System.in); String firstName, lastName; firstName = s.next(); lastName = s.next(); System.out.println("My name is " + firstName +" "+lastName); } }

22nd Dec 2016, 4:50 AM
Griffith
4 Answers
+ 7
Because you didn't close your Scanner. thats why you will get only warning like Resource leak: 's' is never closed... So you can fix that warning with s.close(); Note: You should always write code with try-catch block. Try this Way.. import java.util.Scanner; public class MyClass { public static void main(String[] args) { try{ Scanner s = new Scanner(System.in); String firstName, lastName; firstName = s.next(); lastName = s.next(); System.out.println("My name is " + firstName +" "+lastName); s.close(); }catch(Exception e){ e.printStackTrace(); } } }
22nd Dec 2016, 5:17 AM
Piyush Gupta
Piyush Gupta - avatar
+ 3
That worked Thanks,
22nd Dec 2016, 5:28 AM
Griffith
+ 1
since it's defined out of the main method, it has to be accesable to the rest of the program, since it's private can be only accessed within the class it's defined it. I would of defined it like this tho, import java. util. Scanner; public class myclass{ private static Scanner s= new Scanner(System.in)... }
6th Jan 2017, 3:07 AM
Abrahale Kiros
Abrahale Kiros - avatar
- 1
jxgkciv
6th Jan 2017, 6:45 PM
Deepak Munna
Deepak Munna - avatar