简体   繁体   English

带有扫描文件的练习

[英]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. 您还可以在while循环的每次迭代中消耗两个令牌,并打印出第一个(偶数)个令牌。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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