问题
I'm doing the scanner for a static method, and occur this exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
My modify method tends to get 2 string as input from the console, but it doesn't work.
NOTE: I didn't use scanner.close();
static ArrayList<Book> modBook(){
Book tempbook = Book.searchTitle();
if(tempbook !=null){
Scanner sc = new Scanner(System.in);
int i = BookList.indexOf(tempbook);
System.out.println("Please enter title:");
String booktitle = sc.nextLine();
System.out.println("Please enter author:");
String bookauthor = sc.nextLine();
tempbook.setTitle(booktitle);
tempbook.setAuthor(bookauthor);
BookList.set(i, tempbook);
}
return BookList;
}
My search method:
static Book searchTitle(){
try (Scanner input = new Scanner(System.in)) {
String booktitle;
System.out.println("Please enter title:");
booktitle = input.nextLine();
for(Book b : BookList){
if(b.getTitle() != null && b.getTitle().equals(booktitle)){
System.out.println(b.toString());
return (Book) b;
}
}
}catch(Exception e){e.getMessage(); return null;}
System.out.println("not found");
return null;
}
回答1:
You are using two instance of java.util.Scanner in static methods. You have to used only one instance of java.util.Scanner. Remove the two instances of java.util.Scanner and add this as global variable.
static Scanner input = new Scanner(System.in);
Then used input ONLY to do all the readings in your code. Make sure you close input when you done with it.
回答2:
UPDATE: try-with-resources block close what inside the curve bracket ()
. So, it did close the InputStream, then, just remove it. THANKS
static Book searchTitle(){
Scanner input = new Scanner(System.in))
String booktitle;
System.out.println("Please enter title:");
booktitle = input.nextLine();
for(Book b : BookList){
if(b.getTitle() != null && b.getTitle().equals(booktitle)){
System.out.println(b.toString());
return (Book) b;
}
System.out.println("not found");
return null;
}
来源:https://stackoverflow.com/questions/43964764/scanner-nextline-exception-no-line-found