如何使用扫描仪检查行尾? [英] How to check the end of line using Scanner?

查看:61
本文介绍了如何使用扫描仪检查行尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了类似的问题,但没有帮助.

I have searched similar questions, but none helped.

考虑一个文件:

你好吗?
你在哪里?

hi how are you?
where were you?

我想在每行结束后进行一些操作.如果我使用next(),它不会告诉我何时到达第一行的末尾.

I want to do few operations after the end of every line. If I use next() it wont tell me when I have reached the end of the first line.

我也看过hasNextLine(),但是它只会告诉我是否存在另一行.

Also I have seen hasNextLine() but it only tells me if there exists another line or not.

推荐答案

请考虑使用多个扫描仪,一个扫描仪获取每一行,另一扫描仪在收到每一行之后进行扫描.我唯一要说明的是,使用完内部扫描仪后,请务必确保将其关闭.实际上,在使用完所有扫描仪后,您将需要关闭它们,但特别是内部扫描仪,因为它们会增加和浪费资源.

Consider using more than one Scanner, one to get each line, and the other to scan through each line after you've received it. The only caveat I must give is that you must be sure to close the inner Scanner after you're done using it. Actually you will need to close all Scanners after you're done using them, but especially the inner Scanners since they can add up and waste resources.

例如

Scanner fileScanner = new Scanner(myFile);
while (fileScanner.hasNextLine()) {
  String line = fileScanner.nextLine();

  Scanner lineScanner = new Scanner(line);
  while (lineScanner.hasNext()) {
    String token = lineScanner.next();
    // do whatever needs to be done with token
  }
  lineScanner.close();
  // you're at the end of the line here. Do what you have to do.
}
fileScanner.close();

这篇关于如何使用扫描仪检查行尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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