重置.nextLine()扫描程序 [英] Resetting a .nextLine() Scanner

查看:106
本文介绍了重置.nextLine()扫描程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Java来说,我是业余爱好者,所以请原谅我的问题,如果它看起来很愚蠢
:-P
我有以下代码,用于计算a中的行数file:

I am a rank amateur when it comes to Java, so please pardon my question if it seems dumb :-P I have the following code which is designed to count the number of lines in a file:

while (scanNumOfLines.hasNextLine())    
    {
    NumOfLines ++;
    scanNumOfLines.nextLine();
    }
    System.out.println("NumOfLines = "+NumOfLines);

所以它很好,但我想重新使用扫描仪用于其他目的,但是nextLine已移动到文件的最后一行,我想将其重置回第一行。

So it counts fine, but I want to re-use the scanner for another purpose, but the nextLine has moved to the last line of the file, and I want to reset it back to the first line.

(相反,我不得不使用另一台扫描仪用于其他目的,对我来说这看起来不像它应该那么优雅。)

(Instead, I had to use another scanner for the other purpose, and to me this seems less elegant than it should be.)

我确定必须有一个扫描仪方法将计数器重置为零?

I'm sure there must be a scanner method that resets the counter to zero?

谢谢

CJ

推荐答案

这是不可能的。

不包含它的原因是它支持的各种输入类型。一个例子是流。它们在传递后不会存储结果,因此它们不支持重置。

The reason to not include it, is the wide range of input types it supports. One example is streams. These don't store the results after they have been passed on, so they don't support resetting.

所以优雅的方法是创建一个新的 Scanner 。如果您为其提供了许多自定义设置,请创建工厂方法。

So the elegant way is to create a new Scanner. If you give it many custom settings, create a factory method.

这篇关于重置.nextLine()扫描程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆