How to check the end of line using Scanner?

匆匆过客 提交于 2019-11-30 07:03:54

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.

e.g.,

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();

You can scan the text line by line and split each line in tokens using String.split() method. This way you know when one line has ended and also have all the tokens on each line:

Scanner sc = new Scanner(input);
while (sc.hasNextLine()){
    String line = sc.nextLine();
    if (line.isEmpty())
        continue;
    // do whatever processing at the end of each line
    String[] tokens = line.split("\\s");
    for (String token : tokens) {
        if (token.isEmpty())
            continue;
        // do whatever processing for each token
    }
}

Not sure if this is relevant or too late when i read this. I am relatively new to Java but this seemed to work for me when i encountered a similar problem. I just used a DO-WHILE loop with a End of file specifier denoted by a simple string.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;`enter code here`

public class Main {
    public static void main(String[] args) {
        List<String> name = new ArrayList<>();
        Scanner input = new Scanner(System.in);
        String eof = "";

        do {
            String in = input.nextLine();
            name.add(in);
            eof = input.findInLine("//");
        } while (eof == null);

        System.out.println(name);
     }
}

You can use Scanner and the method you mentioned:

        Scanner scanner = new Scanner(new File("your_file"));
        while(scanner.hasNextLine()){
            String line = scanner.nextLine();
            // do your things here
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!