Scanner class 的 nextInt 方法是 Java 中的访问器还是修改器?

Is the nextInt method of the Scanner class an accessor or a mutator in Java?

我的教科书将增变器方法定义为修改其操作对象的方法。

并且,它将访问器方法定义为一种在不更改对象的情况下向对象查询某些信息的方法。

我说 nextInt 是一种访问方法是否正确?

我的理由是 nextInt 不会修改它操作的对象。如果我创建了一个调用的 Scanner 对象,当我写 "int a = in.nextInt();" 它不会修改实际的 Scanner 对象。相反,它被用作一种 getter 方法来为 a.

赋值

实际上,来自 javadoc:

public int nextInt(int radix)

Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

...

这表明扫描仪的状态在调用该方法后发生了改变。所以这使得 nextInt 成为一个变元。

因此,nextInt既是增变器又是存取器。

你是部分正确的@Nishant。 Scanner class 中的 nextInt() 方法执行 return 下一个要作为键盘输入给出的值。但是我们总是只对 java 中的吸气剂使用 'mutator',即 return 对象的指定 属性。所以我们不能将 nextInt() 命名为一个增变器。要回答您的问题, nextInt() 既不是访问器也不是修改器。希望我说清楚了。