gpt4 book ai didi

java - 扫描仪 nextLine() 异常 : no line found

转载 作者:行者123 更新时间:2023-11-29 08:36:11 24 4
gpt4 key购买 nike

我正在为一个静态方法做扫描器,并发生这个异常:

Exception in thread "main" java.util.NoSuchElementException: No line found

我的修改方法倾向于从控制台获取 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;
}

我的搜索方法:

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;
}

最佳答案

您在静态方法中使用了 java.util.Scanner 的两个实例。您只需使用 java.util.Scanner 的一个实例。删除 java.util.Scanner 的两个实例并将其添加为全局变量。

static Scanner input = new Scanner(System.in);

然后使用输入ONLY 来完成代码中的所有读数。确保在完成输入后关闭输入。

关于java - 扫描仪 nextLine() 异常 : no line found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43964764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com