I'm a learner (very basic for now). I ask question when I don't find a legit answer.
Can I declare scanner in public class so I don't need to declare in every function I use?
public class name
{
//can i declare scanner here? and how?
public static int xxx2(int kk)
{
Scanner kb=new Scanner( System.in);
//code
return kk;
}
public static int xxx1(int kk)
{
Scanner kb=new Scanner(System.in);
//code
}
}
Yes, you can just keep the Scanner
as a record. Since you're using System.in
, you can just initialize it inline, and don't have to worry about closing it:
public class MyClass {
private static Scanner myScanner = new Scanner(System.in);
// Methods that can use myScanner
}
Yes! You can initialize variable/objects in class level also. But the executable code should be in methods only such as any expression
public class MyClass{
//this is allowed in class
private Scanner scanner = new Scanner(System.in);
public void myScannerGet(){
String s = scanner.readLine();
//this must be inside method
System.out.println(s);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.