【问题标题】:How can I make the scanner search for a token, then return the one after it?我怎样才能让扫描仪搜索一个令牌,然后返回它后面的那个?
【发布时间】:2014-11-27 19:52:30
【问题描述】:

我想要ArrayList<String> 中的字符串inningbattingTeamoutsballsstrikes。 换句话说,我需要紧跟标签@attribute 的字符串。 @relation@data 以及该行后面的任何内容都不应出现在此 ArrayList 中。

@关系统计

@属性局真实

@attribute battingTeam {0,1}

@attribute 输出 {0,1,2}

@属性球{0,1,2,3}

@attribute 触发 {0,1,2}

@数据 1,0,0,0,1,"CX",0,0,"crisc001","R","crisc001","R","wilsc004","L","wilsc004","L", "","","","T","F",8,1,no

这是我的主要方法:

public static void main(String[] args) throws IOException
{
    File file = new File("2013ALL.csv");

    Scanner scanFile = new Scanner(file);
    Scanner option = new Scanner(System.in);
    ArrayList<String> headers = new ArrayList<String>();


    String line = "";

    while (!line.startsWith("@attribute"));
    {
        line = scanFile.nextLine();
    }

    do
    {
        line = scanFile.nextLine();
        String[] splitLine = line.split(" ");
        headers.add(splitLine[1]);
    }
    while (line.startsWith("@attribute"));
    System.out.println(headers);
}

【问题讨论】:

    标签: java file search input java.util.scanner


    【解决方案1】:
    public static void main(String[] args) throws Exception {
    
        List<String> headers = new ArrayList<String>();
        Scanner s = new Scanner(new File("2013ALL.csv"));
        String l = s.nextLine();
        while (s.hasNextLine() && l.startsWith("@")) {
            if (l.startsWith("@attribute")) {
                String[] splitLine = l.split(" ");
                headers.add(splitLine[1]);
            }
            l = s.nextLine();
        }
    
        System.out.println(headers);
    }
    

    此代码仅在@attribute 标记之后添加元素。请注意,它不会进行任何错误检查,例如在尝试访问索引 1 处的元素之前检查splitLinelength

    【讨论】:

    • 这行得通。我假设现在扫描仪的位置使得我可以像普通 csv 一样读取文件的其余部分(在 @data 行之后)?
    • @ReiHinoX 在while 循环之后,Scanner 遍历了整个文件。如果您希望while@data 之后立即停止,您可以在循环中添加一个条件,例如:while (s.hasNextLine() &amp;&amp; l.startsWith("@")) ... ,因此Scanner 将位于不以@ 开头的下一行。我建议您使用BufferedReader 来读取文件,因为它具有更好的性能并允许您使用markreset 的位置。 (docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html)
    • 如果我添加该条件,l 在第一次触发循环时将没有值。因此条件l.startsWith("@") 将自动为假,循环永远不会执行。
    • @ReiHinoX 我更新了代码,以便您可以使用l.startsWith("@") 条件。
    猜你喜欢
    • 2015-12-19
    • 1970-01-01
    • 2012-10-07
    • 2014-06-15
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多