2012-10-24 20 views
35

Sono nuovo nell'usare Java, ma ho alcune precedenti esperienze con C#. Il problema che sto avendo arriva con la lettura dell'input dell'utente dalla console.java.util.NoSuchElementException - Lettura scanner input utente

sto correndo nell'errore "java.util.NoSuchElementException" con questa porzione di codice:

payment = sc.next(); // PromptCustomerPayment function 

Ho due funzioni che ottengono l'input dell'utente:

  • PromptCustomerQty
  • PromptCustomerPayment

Se non si chiama PromptCustomerQty, quindi non ge Questo errore mi porta a credere che sto facendo qualcosa di sbagliato con lo scanner. Di seguito è riportato il mio esempio di codice completo. Apprezzo qualsiasi aiuto.

public static void main (String[] args) { 

    // Create a customer 
    // Future proofing the possabiltiies of multiple customers 
    Customer customer = new Customer("Will"); 

    // Create object for each Product 
    // (Name,Code,Description,Price) 
    // Initalize Qty at 0 
    Product Computer = new Product("Computer","PC1003","Basic Computer",399.99); 
    Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99); 
    Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23); 

    // Define internal variables 
    // ## DONT CHANGE 
    ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products 
    String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output 

    // Add objects to list 
    ProductList.add(Computer); 
    ProductList.add(Monitor); 
    ProductList.add(Printer); 

    // Ask users for quantities 
    PromptCustomerQty(customer, ProductList); 

    // Ask user for payment method 
    PromptCustomerPayment(customer); 

    // Create the header 
    PrintHeader(customer, formatString); 

    // Create Body 
    PrintBody(ProductList, formatString); 
} 

public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList) { 
    // Initiate a Scanner 
    Scanner scan = new Scanner(System.in); 

    // **** VARIABLES **** 
    int qty = 0; 

    // Greet Customer 
    System.out.println("Hello " + customer.getName()); 

    // Loop through each item and ask for qty desired 
    for (Product p : ProductList) { 

     do { 
     // Ask user for qty 
     System.out.println("How many would you like for product: " + p.name); 
     System.out.print("> "); 

     // Get input and set qty for the object 
     qty = scan.nextInt(); 

     } 
     while (qty < 0); // Validation 

     p.setQty(qty); // Set qty for object 
     qty = 0; // Reset count 
    } 

    // Cleanup 
    scan.close(); 
} 

public static void PromptCustomerPayment (Customer customer) { 
    // Initiate Scanner 
    Scanner sc = new Scanner(System.in); 

    // Variables 
    String payment = ""; 

    // Prompt User 
    do { 
    System.out.println("Would you like to pay in full? [Yes/No]"); 
    System.out.print("> "); 

    payment = sc.next(); 

    } while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no"))); 

    // Check/set result 
    if (payment.toLowerCase() == "yes") { 
     customer.setPaidInFull(true); 
    } 
    else { 
     customer.setPaidInFull(false); 
    } 

    // Cleanup 
    sc.close(); 
} 

risposta

86

Questo mi ha davvero perplesso per un po 'ma questo è quello che ho trovato alla fine.

Quando si chiama, sc.close() nel primo metodo, non solo si chiude lo scanner ma si chiude anche lo stream di input System.in.È possibile verificarlo stampando il suo stato in cima al secondo metodo come:

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

Così, ora quando si ri-instantiate, Scanner nel secondo metodo, non trova alcun System.in flusso aperto e quindi la eccezione.

Dubito se c'è qualche via d'uscita per riaprire System.in perché:

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.**

L'unica buona soluzione per il vostro problema è quello di avviare la Scanner nel metodo principale, passare che come argomento in due metodi, e chiudere di nuovo nel metodo principale per esempio:

main metodo blocco di codice relativo:

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(); 

I suoi metodi:

public static void PromptCustomerQty(Customer customer, 
          ArrayList<Product> 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 
} 

Spero che questo ti dà una certa comprensione per il fallimento e la possibile risoluzione.

+4

Grazie per la risposta. La tua spiegazione di cosa sta realmente accadendo dietro le quinte è molto utile – fortune

+0

Grazie per la tua risposta. In realtà è vero! – d3vpasha

+0

Oh mio Dio, sono rimasto bloccato per così tanto tempo finché non ho trovato questo post. Grazie mille! Sei fantastico. –

15

Il problema è

Quando uno scanner è chiuso, si chiuderà la sua sorgente di ingresso se la sorgente implementa l'interfaccia Closeable.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Così scan.close() chiude System.in.

per risolvere il problema si può fare

Scanner scanstatic e non chiuderlo in PromptCustomerQty. Il codice qui sotto funziona.

public static void main (String[] args) { 

// Create a customer 
// Future proofing the possabiltiies of multiple customers 
Customer customer = new Customer("Will"); 

// Create object for each Product 
// (Name,Code,Description,Price) 
// Initalize Qty at 0 
Product Computer = new Product("Computer","PC1003","Basic Computer",399.99); 
Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99); 
Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23); 

// Define internal variables 
// ## DONT CHANGE 
ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products 
String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output 

// Add objects to list 
ProductList.add(Computer); 
ProductList.add(Monitor); 
ProductList.add(Printer); 

// Ask users for quantities 
PromptCustomerQty(customer, ProductList); 

// Ask user for payment method 
PromptCustomerPayment(customer); 

// Create the header 
PrintHeader(customer, formatString); 

// Create Body 
PrintBody(ProductList, formatString); 
} 

static Scanner scan; 

public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList)    { 
// Initiate a Scanner 
scan = new Scanner(System.in); 

// **** VARIABLES **** 
int qty = 0; 

// Greet Customer 
System.out.println("Hello " + customer.getName()); 

// Loop through each item and ask for qty desired 
for (Product p : ProductList) { 

    do { 
    // Ask user for qty 
    System.out.println("How many would you like for product: " + p.name); 
    System.out.print("> "); 

    // Get input and set qty for the object 
    qty = scan.nextInt(); 

    } 
    while (qty < 0); // Validation 

    p.setQty(qty); // Set qty for object 
    qty = 0; // Reset count 
} 

// Cleanup 

} 

public static void PromptCustomerPayment (Customer customer) { 
// Variables 
String payment = ""; 

// Prompt User 
do { 
System.out.println("Would you like to pay in full? [Yes/No]"); 
System.out.print("> "); 

payment = scan.next(); 

} while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no"))); 

// Check/set result 
if (payment.toLowerCase() == "yes") { 
    customer.setPaidInFull(true); 
} 
else { 
    customer.setPaidInFull(false); 
} 
} 

Su un lato nota, non si dovrebbe usare == for String confronto, utilizzare .equals invece.

+0

Ma sono in diversi metodi, giusto? Dove sono creati e chiusi. –

+0

Nel codice originale sono. Nel codice fisso utilizzo un'istanza Scanner per entrambi i metodi. –

+0

Sono ancora perplesso perché 'sc.next()' o anche 'sc.nextLine()' nel secondo metodo causano l'eccezione. –

0

Dopo questa linea:

qty = scan.nextInt(); 

Aggiungere sempre una linea più per cancellare lo scanner:

scan.nextLine(); 

Inoltre, utilizzare

sc.nextLine(); 

invece di

sc.next(); 
+0

Aggiunto scan.nextLine(); e cambiato sc.next() in sc.nextLine() ;, ma sto ancora ricevendo l'errore. – fortune

Problemi correlati