Phi*_*ong 1 java java.util.scanner
我正在为一个静态方法做扫描仪,并发生这个异常:
Exception in thread "main" java.util.NoSuchElementException: No line found
Run Code Online (Sandbox Code Playgroud)
我的修改方法倾向于从控制台获取 2 个字符串作为输入,但它不起作用。
注意:我没有使用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;
}
Run Code Online (Sandbox Code Playgroud)
我的搜索方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
您在静态方法中使用java.util.Scanner 的两个实例。您只需要使用java.util.Scanner 的一个实例。删除 java.util.Scanner 的两个实例并将其添加为全局变量。
static Scanner input = new Scanner(System.in);
Run Code Online (Sandbox Code Playgroud)
然后仅使用 input来完成代码中的所有读数。确保在完成输入后关闭输入。