Java - Scanner抛出NoSuchElementException:找不到行

时间:2017-07-28 15:43:19

标签: java nosuchelementexception

在我的程序中,我有一种从文本文件中选择帐户的方法。但是当编译器到达用户输入其选择的行时,它会抛出异常NoSuchElementException:找不到行。请帮帮我。

private int chooseAcc() throws IOException {
    int choice = -1;
    int numOfLine = 0;
    do {
        if (file.exists() && !file.isDirectory()) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader(file));
                while (br.readLine() != null) {
                    numOfLine++;
                }

            } catch (FileNotFoundException ex) {
                ex.printStackTrace();
            } finally {
                br.close();
            }
        }

        System.out.print("Enter the option: ");
        try {
            choice = Integer.parseInt(sc.nextLine()); //stack trace error here
        } catch (NumberFormatException e) {
            System.out.println("Error");
        }
        if (choice < 0 || choice > numOfLine) {
            System.out.println("Error");
        }
    } while (choice < 0 || choice > numOfLine && numOfLine == 0);
    return choice;
}

0 个答案:

没有答案