[英]Instantiate Java Scanner in class or method
我创建了一个类来读取用户输入。 我正在使用扫描仪来获取用户输入并对其进行消毒。 当使用扫描仪对象时,我想到了这两种方法中哪一种最佳实践的问题:
要在类中创建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; }
要创建一个Scanner引用类 - >在每个方法中实例化它 - >在每个方法中使用它
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的方法可能无法得到正确的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.