首页 > 解决方案 > 逐行阅读字母

问题描述

我现在有这段代码可以读取 txt 文档的行。我正在尝试添加一些代码,以便程序只打印以字母 C 和 A 开头的文本行。有人可以帮我吗?

import java.io.*;
import java.util.*;
public class FileTester
{
    public static void main(String args[]) throws IOException
    {
        Scanner sf = new Scanner(new File("amazinggrace.txt"));
        int maxIndx = -1;
        String text[] = new String[1000];

        while(sf.hasNext( ))
        {
            maxIndx++;
            text[maxIndx] = sf.nextLine( ) ;
        }
        sf.close( );
        {
            System.out.println( text[j] );
        }
    }
}

标签: java

解决方案


您可以使用String.startsWith()while 循环内部的方法来检查该行是否以特定字符/字符开头,然后System.out.println()像稍后在代码中那样使用来打印该行。

您可以在此处找到文档String.startsWith()https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#startsWith(java.lang.String)


推荐阅读