在类或方法中实例化Java扫描程序

在类或方法中实例化Java扫描程序,java,java.util.scanner,instantiation,Java,Java.util.scanner,Instantiation,我创建了一个类来读取用户输入。我正在使用扫描仪获取用户输入并对其进行消毒。使用scanner object时,我突然想到以下两种方法中的哪一种是最佳做法: 在类中创建Scanner引用并实例化它->在每个方法中使用它 private Scanner sc = new Scanner(System.in); public int readInt() { int input = sc.nextInt(); // some code to restrict in

我创建了一个类来读取用户输入。我正在使用扫描仪获取用户输入并对其进行消毒。使用scanner object时,我突然想到以下两种方法中的哪一种是最佳做法:

  • 在类中创建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;    
    
    }
    
  • 创建扫描程序引用类->在每个方法中实例化它->在每个方法中使用它

    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引用的方法。 另一方面,在多线程模型中,创建扫描引用的方法
在课堂上可能得不到正确的答案。

如何在要读取的方法中创建扫描程序,并将其作为参数传递给这些方法?这是最好的选择,国际海事组织。在第一种情况下,小心
nextLine
,然后是
nextLine
。。(如果您的代码中有
readLine
)@JBNizet谢谢。这确实是一个很好的选择。然而,对于更优雅的代码,我想处理这个类中的所有Scanner对象,并只在这里导入它。