Resetting a .nextLine() Scanner

后端 未结 5 487
生来不讨喜
生来不讨喜 2020-12-03 17:42

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 f

5条回答
  •  盖世英雄少女心
    2020-12-03 18:09

    You will have to redeclare the Scanner. When you invoke nextLine(), the line is removed from the buffer and effectively discarded from the Scanner.

    So, essentially, there is a method to do that: it's the constructor.

    Scanner scanNumOfLines = new Scanner(myFile);
    

    There is no "counter" in the Scanner object. Instead think of it as more like a conveyor belt. The belt has no knowledge or care about what's on it. It just keeps spitting things out at you while there are items left on it. And once you take them, they're gone from it for good.

提交回复
热议问题