【问题标题】:Why would this simple code throw "NoSuchElementException"?为什么这个简单的代码会抛出“NoSuchElementException”?
【发布时间】:2016-09-18 00:47:11
【问题描述】:

somefile.txt 有如下输入,newfile.txt 为空。

China
1330044605
India
1147995898
United States
303824646

这两个文件都在我的桌面上。

public class NextMethod {

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

        File inputFile = new File("/home/cyn/Desktop/somefile.txt");
        Scanner in = new Scanner(inputFile);
        PrintWriter writer = new PrintWriter("/home/cyn/Desktop/newfile.txt");


        while (in.hasNextLine()) {

            String coName = in.nextLine();
            int peopCo = in.nextInt();
            in.nextLine();
            writer.println(coName);
            writer.println(peopCo);

        }

        in.close();
        writer.close();

    }

}

【问题讨论】:

  • 我已尽我所能修正了您的问题措辞和格式。这里缺少的其他主要内容是完整的异常,包括堆栈跟踪以及它发生在哪一行。

标签: java io


【解决方案1】:

我可以通过在someFile.txt 末尾添加一个空行来复制您的问题。

这与javadoc 中记录的行为一致。

抛出:NoSuchElementException - 如果没有找到行

检查以确保您的输入文档中没有任何意外的空白。

【讨论】:

    猜你喜欢
    • 2015-02-19
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多