如何跳过用扫描仪读取一行

时间:2017-03-09 02:50:59

标签: java java.util.scanner

我已阅读文本文件并正在扫描该文件。我的问题是如何跳过包含某个字符的行(在我的情况下以" //""""(空格)开头的行。

这是我目前的代码。有人能指出我正确的方向吗?

    File dataFile = new File(filename);
    Scanner scanner = new Scanner(dataFile);


      while(scanner.hasNext())
      {
         String lineOfText = scanner.nextLine();
         if (lineOfText.startsWith("//")) {
           System.out.println(); // not sure what to put here
         }
      System.out.println(lineOfText);
      }
   scanner.close();

5 个答案:

答案 0 :(得分:2)

如果文本行不以/或空格开头,您只需要在while循环中执行代码。您可以按如下所示过滤掉这些:

while(scanner.hasNext()) {
   String lineOfText = scanner.nextLine();
   if (lineOfText.startsWith("//") || lineOfText.startsWith(" ")) {
      continue; //Exit this iteration if line starts with space or /
   }
   System.out.println(lineOfText);
}

答案 1 :(得分:1)

在迭代文件中的文本行时,使用String的{​​{3}}方法检查行是否以您要避免的序列开头。

如果是,请继续下一行。否则,打印出来。

while (scanner.hasNext()) {
    String lineOfText = scanner.nextLine();

    if (lineOfText.startsWith("//") || lineOfText.startsWith(" ") ) {
        continue;
    }

    System.out.println(lineOfText);
}

答案 2 :(得分:0)

只需使用continue喜欢 -

if (lineOfText.startsWith("//")) {
  continue; //would skip the loop to next iteration from here
}

Detials - What is the "continue" keyword and how does it work in Java?

答案 3 :(得分:0)

如果您只想打印出以“//”开头的代码行,那么您应该在java中使用continue关键字。

String lineOfText = scanner.nextLine();
if (lineOfText.startsWith("//")) {
    continue;
}

有关“continue”关键字的详情,请参阅this post

答案 4 :(得分:0)

您只需插入"否则"在您的代码中:

public static void main(String [] args)抛出FileNotFoundException {

     File dataFile = new File("testfile.txt");
        Scanner scanner = new Scanner(dataFile);


          while(scanner.hasNext())
          {
             String lineOfText = scanner.nextLine();
             if (lineOfText.startsWith("//")) {
               System.out.println(); 
             }
             else
                 System.out.println(lineOfText);
          }
       scanner.close();
}

}

相关问题