最近,我在一本书中读到有关将用户定义的类作为输入传递给扫描器的内容,但它并没有解释其背后的逻辑。这是程序
import java.nio.CharBuffer;
import java.util.Random;
import java.util.Scanner;
class ScannerInputBase implements Readable
{
private int count;
Random rand = new Random();
ScannerInputBase(int count) { this.count = count; }
public int read(CharBuffer cb) //read is a method in Readable interface
{
if(count-- == 0)
return -1;
for(int i=0;i<2;i++)
{ cb.append('a'); }
return 1;
}
}
public class ScannerInput {
public static void main (String args[]) {
Scanner input = new Scanner(new ScannerInputBase(5));
while(input.hasNext())
{
print(input.next()+"-");
}
}
}
它的输出是
aaaaaaaaaa-
我有两个问题
这里如何调用 read() 函数?
我的意思是我知道它被隐式地以某种方式调用但是从它被调用的地方。输出中的单个连字符表明 main 函数中的 while 循环仅迭代一次。但为什么只有一次。我期待像 aa-aa-aa-aa-aa-
这样的输出
最佳答案
how read() function is getting called here? i mean i understand it's implicitly geting called somehow but from where it's getting called.
答案就在Scanner
类的next()
方法的源代码中:
public String next() {
....
while (true) {
.....
if (needInput)
readInput();
...
}
}
这将我们带到定义如下的 readInput
方法:
private void readInput() {
......
try {
n = source.read(buf);
} catch (IOException ioe) {
.....
}
.....
}
我们看到 readInput
方法正在调用 source
对象的 read
方法,该对象是 Reader
类的实例并在 Scanner
的对象创建期间作为参数传递给 Scanner
构造函数。
现在,由于您已将 Reader
的子类对象作为参数传递给 Scanner
构造函数。而且,您已经覆盖了类中的 read(CharBuffer)
方法,所以
read
方法的覆盖版本正在被 Scanner.readinput
方法调用。
A single hyphen in the output suggests that while loop in main function is iterated only once. but why only once. I was expecting output like aa-aa-aa-aa-aa-
因为,字符串 aaaaaaaaaa
中没有空格,这是默认的分隔符 Pattern。结果,所有字符串都在单次迭代中读取。因此,hasNext
在第一次迭代后返回 false,while 循环终止。
Note: Always use
@Override
annotation while overriding a method within subclass.
关于java - Scanner 类如何使用用户定义的类作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18251078/