如何创建第二个扫描器来让每个标记用逗号分隔

问题描述 投票:0回答:1

我不知道如何从文本文件中提取每个标记(以获取工具字段的每个值)以创建相应的工具对象以添加到工具列表(工具数组列表)中。我要做的是:

   ...   
   if it's not a comment or a blank line
     create a second scanner passing it lineOfText
     create a Tool object
     pass the scanner to a new readData() method of the Tool
           class & read data for each of its fields
     store the Tool object in toolList
   ...

这是我当前的扫描仪代码:

try (Scanner scanner = new Scanner(new File(filePathAbsolute)))
{
    while (scanner.hasNextLine())
    {
        String lineOfText = scanner.nextLine();
        if (lineOfText.startsWith("//") || lineOfText.isEmpty())
        {
            continue;
        }
        System.out.println(lineOfText);
        Scanner scanner2 = new Scanner(lineOfText).useDelimiter(",");
        while (scanner2.hasNext())
        {
            String[] tokens = scanner.next().split(",");
            
        }
    }
    scanner.close();

我应该从中提取的文本文件(无法编辑任何内容):

// this is a comment, any lines that start with //
// (and blank lines) should be ignored

// data is toolName, itemCode, timesBorrowed, onLoan, cost, weight
Makita BHP452RFWX,RD2001,12,false,14995,1800
Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200     
DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
Bosch GSR10.8-Li Drill Driver,RD3021,25,true,9995,820
 Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200 
DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300 
Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400
java extract delimiter
1个回答
0
投票

你做一件事情太多了,要么你使用定界符,要么你手动拆分线,如果你需要扫描 2 个不同的东西,你可以完全重复使用同一个扫描仪:

try (Scanner scanner = new Scanner(new File(filePathAbsolute)))
{
    while (scanner.hasNextLine())
    {
        String lineOfText = scanner.nextLine();
        if (lineOfText.startsWith("//") || lineOfText.isEmpty())
        {
            continue;
        }
        System.out.println(lineOfText);
        String[] tokens = lineOfText.split(",");
    }
    // scanner.close();
    // Closing your scanner is actually redundant as try-with-resources is already closing your resources automatically at the end of the block
© www.soinside.com 2019 - 2024. All rights reserved.