在java数组列表中搜索而不返回值
我一直在努力改变我的方法,使其无效。但每当我更改它时,它总是打印出书名和错误消息。如何将我的方法更改为无效?
public int displayBookDetails(String bookName) {
for (int i = 0; i < classrooms.size(); i++) {
Library library = librarys.get(i);
if (library.returnBookName().equals(bookName)) {
System.out.println("Index: " + i);
System.out.println(library.returnBookName());
System.out.println(library.authorName());
return i;
}
}
return -1;
System.out.println ("Book name is not valid");
}
Ive been trying to change my method to a void. But whenever I change it, it always prints out the book name and an error message. How can I change my method to a void?
public int displayBookDetails(String bookName) {
for (int i = 0; i < classrooms.size(); i++) {
Library library = librarys.get(i);
if (library.returnBookName().equals(bookName)) {
System.out.println("Index: " + i);
System.out.println(library.returnBookName());
System.out.println(library.authorName());
return i;
}
}
return -1;
System.out.println ("Book name is not valid");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您还需要删除 return 语句(并用简单的 return (无参数)替换第一个语句)。
You need to remove the return statements (and replace the first one by a simple return (no parameter)) too.
尝试这样的事情,我相信它会起作用:
Try something like this, I am sure it will work:
当你找到这本书时,你可能仍然想返回 - 这可能是你之前错过的:
就我个人而言,我可能会将“搜索”与“显示”分开:(
请注意,不存在“当然,此时应该显示“index”。如果您确实还需要显示它,则它需要成为
Library
的一部分。)You probably still want to return when you've found the book - that may be what you've missed before:
Personally I'd probably separate out the "search" from "display":
(Note that there's no such thing as the "index" at this point, of course. If you really need to display that as well, it would need to be part of
Library
.)您可以使用不带值的
return
来实现此目的:You can do so by using
return
without a value:您尝试更改为 void 的返回类型仅表示该方法返回的内容。然而,该方法可能有不同的副作用,如 I/O,例如打印到控制台。不幸的是,没有办法限制 Java 或大多数 OOP 语言中的副作用。函数式编程的目的是消除函数中的所有副作用,以便更容易地推理程序。
The return type you are trying to change to void only signifies what is returned by the method. However the method might have different side-effects like I/O, e.g. printing to the console. Unfortunately there is no way to constrain side-effects in Java or most OOP langauges. Functional programming aims at getting rid of all side effects in your functions, so it can be reasoned about the program more easily.