简体   繁体   中英

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.

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
    }
}

在遍历文件内容时,在行号上使用余数运算符%

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM