【问题标题】:Error: NoSuchElementException错误:NoSuchElementException
【发布时间】:2017-03-05 17:15:53
【问题描述】:

这个程序访问一个文本文件,其中的文本元素用逗号分隔。元素注册在我创建的变量中。除了最后一个。然后发生错误。该程序适用于扫描仪类的默认空白分隔符(文本文件已相应调整),但当我使用逗号作为分隔符时失败。有人可以提供一些见解。

文本数据:

smith,john,10
stiles,pat,12
mason,emrick,12

代码:

public void openFile(String f)
    {   
        try{
            x = new Scanner(new File(f));
            x.useDelimiter(",");
        } catch(Exception e){
            System.out.println("File could not be found please check filepath");
        }

    }

public boolean checkNameRoster()
    {
        openFile(file);
        boolean b = false;
        while(x.hasNext())
        {
            String lName = x.next().trim();
            **String fName = x.next().trim();**
            String grade = x.next().trim();
            if(fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
                {
                    b = true;
                }
        }
        closeFile();
        return b;
    }

【问题讨论】:

    标签: java.util.scanner delimiter nosuchelementexception


    【解决方案1】:

    问题在于您在 Scanner 函数 openFile() 中调用了 x.useDelimiter(",");

    由于您的文本数据是:

    smith,john,10
    stiles,pat,12
    mason,emrick,12
    

    Scanner 认为它是:

    "smith,john,10\nstiles,pat,12\nmason,emrick,12"
    

    所以当你执行你的代码时会发生什么:

    1: x.hasNext() ? Yes
        x.next().trim() => "smith"
        x.next().trim() => "john"
        x.next().trim() => "10\nstiles"
    2: x.hasNext() ? Yes
        x.next().trim() => "pat"
        x.next().trim() => "12\nmason"
        x.next().trim() => "emrick"
    3: x.hasNext() ? Yes
        x.next().trim() => "12"
        x.next().trim() => Error!
    

    要解决此问题,您可以编辑文件并将所有\n 更改为,,或者使用第一个Scanner 获取所有行,然后使用另一个获取令牌,如下所示:

    public void openFile(String f)
        {   
            try{
                x = new Scanner(new File(f)); // Leave default delimiter
            } catch(Exception e){
                System.out.println("File could not be found please check filepath");
            }
    
        }
    
    public boolean checkNameRoster()
        {
            openFile(file);
            boolean b = false;
            while(x.hasNextLine()) // For each line in your file
            {
                Scanner tk = new Scanner(x.nextLine()).useDelimiter(","); // Scan the current line
                String lName = x.next().trim();
                String fName = x.next().trim();
                String grade = x.next().trim();
                if (fName.equalsIgnoreCase(firstName) && lName.equalsIgnoreCase(lastName) && grade.equalsIgnoreCase(grade))
                    {
                        b = true;
                    }
            }
            closeFile();
            return b;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 2021-08-08
      • 1970-01-01
      • 2022-12-03
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多