主线程java.util.NoSuchElementException中的异常

时间:2013-02-08 01:34:00

标签: java

我正在开展这个项目以提高我的Java技能。我的目标是编写一个程序,从指定的文档或文本文件中读取行(取决于用户想要打开的行;分别为int 2或1)。然后要求用户输入他们的文档名称(没有文件扩展名) ),然后读取文档或文本文件中的第一行。我希望它能像用户想要的那样多次这样做。但是我在执行代码时不断获得NoSuchElementException

public class switches {
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        System.out.println("How many files would you like to scan?");
        System.out.println("Enter # of files to scan: ");
        int countInput = input.nextInt();
        input.close();

        for (int count = 0; count < countInput;) {
            System.out.println("Please enter a file name to scan. ");
            System.out.println("1 for .txt, 2 for .doc");
            Scanner keyboard = new Scanner(System.in);
            int choice = keyboard.nextInt();

            switch (choice) {
            default: {
                do {
                    System.out.println("Please pick "
                            + "either 1: txt or 2: doc");
                    choice = keyboard.nextInt();
                } while (choice != 1 && choice != 2);
            }
            case 1: {
                System.out.println("Txt file name:");
                keyboard.nextLine();
                String txtName = keyboard.nextLine();
                File openTxtFile = new File("C:/Users/Hp/Documents/" + txtName
                        + ".txt");
                Scanner firstTxtLine = new Scanner(openTxtFile);
                String printedTxtLine = firstTxtLine.nextLine();
                firstTxtLine.close();
                System.out.println("The first line " + "of your text file is: "
                        + printedTxtLine);
                keyboard.close();
                count++;
                break;
            }
            case 2: {
                System.out.println("Doc file name:");
                keyboard.nextLine();
                String docName = keyboard.nextLine();
                File openDocFile = new File("C:/Users/Hp/Documents/" + docName
                        + ".doc");
                Scanner firstLine = new Scanner(openDocFile);
                String printedDocLine = firstLine.nextLine();
                firstLine.close();
                System.out.println("The first line"
                        + " of your word document is: " + printedDocLine);
                keyboard.close();
                count++;
                break;
            }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

如果您删除第14行上的第input.close();行。这可以解决您的问题。根据{{​​3}},如果输入用尽,它将抛出NoSuchElementException - “。