0

私は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;
            }
            }
        }
    }
}
4

1 に答える 1

2

14行目の行を削除するとinput.close();、問題が解決するはずです。ドキュメントによると、 NoSuchElementException「入力が使い果たされた場合」をスローします。

于 2013-02-08T01:52:59.333 に答える