Count lines Scanner

3

Could someone explain to me how to count the lines of a Scanner text so that after counting it can return to the starting line?

    
asked by anonymous 22.04.2014 / 20:02

1 answer

4

You can transfer all the contents of the Scanner to an ArrayList, so you easily have the number of lines your Scanner had, then you can access or browse 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();
    
22.04.2014 / 20:23