Count Scanner lines

Asked

Viewed 967 times

3

I wonder if someone could explain to me how to count the lines of a Scanner text so that after counting them I can go back to the starting line?

  • Why do you need the amount of lines that Scanner has read? Maybe there is a better option than you are planning

  • basically what I wanted was to "jump" to the last line but I can’t, I’ve tried this :

  • while(.hasNextLine()){ file.next();} but I’m not getting it

  • want to skip a predefined amount of lines? for example, skip the first 10 lines of a scanner?

  • there it is, the number of lines I want to jump is not set

  • what then would be the condition to know how many lines to skip?

  • only even the number of total lines ... the problem is that when counting the number of lines later I can’t get back to the lines above

  • thanks for the help

  • if the answer solved your problem please mark as accepted by clicking on the V of below the score

Show 4 more comments

1 answer

4

You can transfer all Scanner content to an Arraylist, so you can easily have the amount of lines your Scanner has, then you can access or scroll through your Arraylist behind the data that interests you. Example:

List<String> textos = new ArrayList<>();
//le linha por linha enquanto alimenta seu ArrayList
while(sc.hasNext()) {
    textos.add(sc.next());
}
//mostra quantas linhas o Scanner leu
System.out.println("Seu scanner possuia " + textos.size() + " linhas"); 
//mostra o conteúdo da primeira linha
System.out.println("A primeira linha contém: " + textos.get(0));
sc.close();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.