odesordeiro
odesordeiro

Reputation: 5

Exercice with scan files

I have to print the even lines of this file "text", how can I do that?

public static void main(String[] args) throws FileNotFoundException{
    File f =new File("text.txt");
    Scanner scanner = new Scanner(f);

    while(scanner.hasNextLine()){
        System.out.println(scanner.nextLine());
    }
}

Thank you.

Upvotes: 0

Views: 45

Answers (3)

matt
matt

Reputation: 2429

You can also just consume two tokens per iteration of the while loop and print out every first (even) one.

Using a counter is probably clearer though.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class NumberPrinter {
  public static void main(String[] args) throws FileNotFoundException{
    File f =new File("text.txt");
    Scanner scanner = new Scanner(f);

    while(scanner.hasNextLine()){
        System.out.println(scanner.nextLine());
      if (scanner.hasNextLine()) {
        scanner.nextLine();
      }
    }
  }
}

Upvotes: 0

takendarkk
takendarkk

Reputation: 3443

Here is an easy way to keep track of which line you are on and how to tell if it is an even number or not. If it is indeed an even number, then we print it.

public static void main(String[] args) throws FileNotFoundException {
    File f = new File("text.txt");
    Scanner scanner = new Scanner(f);
    int counter = 1; //This will tell you which line you are on

    while(scanner.hasNextLine()) {
        if (counter % 2 == 0) { //This checks if the line number is even
            System.out.println(scanner.nextLine());
        }
        counter++; //This says we just looked at one more line
    }
}

Upvotes: 2

Reimeus
Reimeus

Reputation: 159784

Use the remainder operator % on the line number while iterating over the file contents

Upvotes: 1

Related Questions