Can I declare a Scanner in a public class?

Valentin :

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
    }
}
Mureinik :

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
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115028&siteId=1
Recommended