在类或方法中实例化Java Scanner

我创建了一个类来读取用户输入.我正在使用扫描仪来获取用户输入并对其进行消毒.当使用扫描仪对象时,我想到了这两种方法中哪一种最佳实践的问题:

>在课程中创建扫描仪参考;实例化它 – >在每种方法中使用它

private Scanner sc = new Scanner(System.in);

public int readInt() {

   int input = sc.nextInt();           
   // some code to restrict input to integers only
   return input;    

}

public int readDouble() {

   int double = sc.nextDouble();
   // some code to restrict input to double only
   return input;    

}

>要创建扫描程序引用类 – >在每种方法中实例化它 – >在每种方法中使用它

private Scanner;

public int readInt() {

   sc = new Scanner(System.in);

   int input = sc.nextInt();           
   // some code to restrict input to integers only
   return input;    

}

public int readDouble() {

   sc = new Scanner(System.in);

   int double = sc.nextDouble();
   // some code to restrict input to double only
   return input;    

}

想象一下这样一个场景,即在另一个类中创建该类的对象,并且将多次调用readInt()或readDouble().在这种情况下,从安全和内存的角度来看,上述两种方法中哪一种更实用?

或者正如其中一条评论所暗示的那样,上述都不实用,最好的方法是将扫描仪对象作为参数传递给每个方法?

最佳答案 这个问题太好了,我想宣布我的意见.

一方面,在单线程模型中,在类中创建Scanner引用的方法等同于实例化它的方法.

另一方面,在多线程模型中,创建Scanner refenence的方法

在课堂上可能无法得到正确的答案.

点赞