+ 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); } }
4 ответов
+ 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();
}
}
}
+ 3
That worked Thanks,
+ 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)...
}
- 1
jxgkciv