java.util.NoSuchElementException - Scanner reading user input

后端 未结 4 2155
灰色年华
灰色年华 2020-11-21 05:30

I\'m new to using Java, but I have some previous experience with C#. The issue I\'m having comes with reading user input from console.

I\'m running into the \"java.u

4条回答
  •  不要未来只要你来
    2020-11-21 05:34

    This has really puzzled me for a while but this is what I found in the end.

    When you call, sc.close() in first method, it not only closes your scanner but closes your System.in input stream as well. You can verify it by printing its status at very top of the second method as :

        System.out.println(System.in.available());
    

    So, now when you re-instantiate, Scanner in second method, it doesn't find any open System.in stream and hence the exception.

    I doubt if there is any way out to reopen System.in because:

    public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

    The only good solution for your problem is to initiate the Scanner in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:

    main method related code block:

    Scanner scanner = new Scanner(System.in);  
    
    // Ask users for quantities 
    PromptCustomerQty(customer, ProductList, scanner );
    
    // Ask user for payment method
    PromptCustomerPayment(customer, scanner );
    
    //close the scanner 
    scanner.close();
    

    Your Methods:

     public static void PromptCustomerQty(Customer customer, 
                                 ArrayList ProductList, Scanner scanner) {
    
        // no more scanner instantiation
        ...
        // no more scanner close
     }
    
    
     public static void PromptCustomerPayment (Customer customer, Scanner sc) {
    
        // no more scanner instantiation
        ...
        // no more scanner close
     }
    

    Hope this gives you some insight about the failure and possible resolution.

提交回复
热议问题