[英]How to write the Java hasNext() function for custom scanners
我在互联网上找到了许多自定义 Scanner 类,用于快速 Java IO,但它们都没有提供自定义 hasNext() 方法实现,所以我不知道如何在输入可变大小时读取数据。
这是这些类之一的示例:
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
我怎么能 go 关于自己写这个? 谢谢。
Unfortunately the BufferedReader doesn't have a hasNext()
function but it includes a ready()
function which is a boolean function that tells if there is an input to be read or not, You can find about it here https://docs. oracle.com/javase/8/docs/api/java/io/BufferedReader.html#ready-- 。
因此,如果您想添加到 class 您提到它将 go 像这样:
static boolean ready() throws IOException {return reader.ready();}
但是请注意,如果输入不存在, ready()
将返回 false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.