Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在switch语句中读取用户输入时发生java.util.NoSuchElementException_Java - Fatal编程技术网

在switch语句中读取用户输入时发生java.util.NoSuchElementException

在switch语句中读取用户输入时发生java.util.NoSuchElementException,java,Java,我正在为一门计算机科学课程工作,在这个项目中遇到了一个错误,希望有人能让我了解可能发生的事情。代码中发生的一些背景信息: 在下面的代码中,我启动了我的程序,它显示一个UI菜单,请求用户输入,并使用switch语句根据用户输入运行适当的方法 /** * Start of program */ public static void main(String[] args) { Library library = new Library();

我正在为一门计算机科学课程工作,在这个项目中遇到了一个错误,希望有人能让我了解可能发生的事情。代码中发生的一些背景信息:

在下面的代码中,我启动了我的程序,它显示一个UI菜单,请求用户输入,并使用switch语句根据用户输入运行适当的方法

    /**
     * Start of program
     */
    public static void main(String[] args) {

        Library library = new Library();

        char userChoice; //Stores what menu item the user chose
        Scanner userMenuChoiceScanner = new Scanner(System.in);
        boolean loop = true;

        displayMenu(); //Displays main UI menu
        userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0)); //Gets user's menu choice

        /*Loops UI menu afer user has made menu choice and exits loop if user choses 'q' from menu.*/
        while(loop) {

            /* Switch descides what menu choice user has made and whether to prin menu UI again, load, 
             * search, print, or analyze a music catalog, or to quit program.
             */
            switch(userChoice) {
            case 'm':
                System.out.println();
                displayMenu();
                userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
                break;
            case 'p':
                System.out.println();

                if(library.getBooks().size() != 0) {
                    printLibrary(library);
                } else {
                    System.out.println("There are no books in the library. Please add a book first.");
                }

                System.out.print("Please enter a command (press 'm' for Menu):");
                userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
                break;
            case 'a':
                System.out.println();
                addBookToLibrary(library);
                System.out.print("Please enter a command (press 'm' for Menu):");
                userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
                break;
            case 'd':

                System.out.println();

                if(library.getBooks().size() != 0) {
                    deleteBookFromLibrary(library);
                } else {
                    System.out.println("There are no books in the library. Please add a book first.");
                }

                System.out.print("Please enter a command (press 'm' for Menu):");
                userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
                break;
            case 'r':           
                System.out.println();

                if(library.getBooks().size() != 0) {
                    readBookFromLibrary(library);
                } else {
                    System.out.println("There are no books in the library. Please add a book first.");
                }

                System.out.print("Please enter a command (press 'm' for Menu):");
                userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
                break;
            case 'q':
                System.out.println();
                System.out.println("Thank you! Goodbye!");
                loop = false;
                break;
            default:
                System.out.println();
                System.out.println("Invalid selection!");
                System.out.print("Please enter a command (press 'm' for Menu):");
                userChoice = Character.toLowerCase(userMenuChoiceScanner.nextLine().charAt(0));
                System.out.println();

            }
        }

        userMenuChoiceScanner.close();



    }
发生的情况是,当用户做出选择时,它进入适当的方法并在那里完成任务,然后当它返回到switch语句以获取新的用户输入时,它抛出java.util.NoSuchElementException错误,就像扫描程序流被关闭一样,但我不会关闭扫描仪,直到最后流应该仍然是开放的

switch语句的设置方式是,必须添加一本书。用户必须先选择“a”,然后才能选择任何其他选项。下面是addBookToLibrary方法的代码,该方法有一对打开和关闭的扫描仪。我想可能是关闭这些扫描仪导致了这个问题

    /**
     * Adds new book to library
     * @param library ArrayList object which holds book objects
     */
    public static void addBookToLibrary(Library library) {
        Scanner addBookScanner = new Scanner(System.in);
        String title = "";
        String author = "";
        String genre = "";
        String filename = "";
        boolean addStatus = false;


        /*Asks user for book details */
        System.out.println("Enter the details of the book you want to add to the library:");
        System.out.println("What is the book title?");
        title = addBookScanner.nextLine();
        System.out.println("What is the author's name?");
        author = addBookScanner.nextLine();
        System.out.println("What is book genre?");
        genre = addBookScanner.nextLine();
        System.out.println("What is the book's filename?");
        filename = addBookScanner.nextLine();
        addBookScanner.close();

        Book newBook = new Book(author, title); //creates new book with author and title set

        newBook.setGenre(genre); //sets book genre

        File bookFile = new File(System.getProperty("user.dir") + '\\' + filename); //used to check if file user provided exists
        System.out.println(bookFile);
        /*Checks to see if file user provided actually exists*/
        if(bookFile.exists()) {

            try {

                newBook.setFilename(filename);

            }catch(Exception e) {

            }

        }
        else {

            Scanner getNewFilenameScanner = new Scanner(System.in);

            //Continues to ask user for new filename if file doesn't exist
            do {
            System.out.println("I'm sorry, but the file you specified does not exist.");
            System.out.print("Enter a new file name:");
            bookFile = new File(getNewFilenameScanner.nextLine());

            }while (!(bookFile.exists()));

            getNewFilenameScanner.close();
        }

        addStatus = library.addBook(newBook); //adds book to library

        if(addStatus) {
            System.out.println("Book was successfully added!");
        }
        else {
            System.out.println("Book was not successfully added. Please try again.");
        }
    }
这段代码在以前的项目中工作得很好,所以我不确定为什么它现在不工作。任何帮助都将不胜感激

非常感谢您使用addBookToLibrary方法,在使用完扫描仪后关闭扫描仪。但是,这些扫描仪连接到System.in标准输入流。根据报告,关闭这些扫描仪也将关闭标准输入流

还有什么连接到标准输入流?userMenuChoiceScanner!标准输入流关闭后,userMenuChoiceScanner无法从中读取,因此引发异常

请注意,尽管userMenuChoiceScanner直到最后才关闭,但它所读取的流是关闭的

事实上,您不需要在这里创建多个扫描仪。您只需要使用一个扫描仪,并将其传递给不同的方法。例如,addBookToLibrary可以接受扫描仪:

它将只使用s来读取输入。您可以将userMenuChoiceScanner传递给它:


一般来说,你不应该关闭任何你没有打开的东西。您没有打开JVM所打开的标准输入流,因此不应该关闭它。

您可能应该将displayMenu行和读取用户选择的行也放在循环中。我不想每次都显示菜单,但我继续将读取用户选择的行放在循环中,它是否起作用?不,结果没有改变。仍在获取异常。您选择了哪个选项?
public static void addBookToLibrary(Library library, Scanner s) {
addBookToLibrary(library, userMenuChoiceScanner);