I'd like to print out that I can't find the books that are not in the array, although I want just one sentence "no data".
Please give me some advice.
You can add a boolean that gets updated once the book is found, and once you are done from the loop, it will print 'no data' if the book wasn't found, something like this:
public static void main(String[] args)
{
Book[] book = {new Book("java", 150, 2016), new Book("python", 100, 2019), new Book("javascript", 200, 2018)};
Scanner in = new Scanner(System.in);
System.out.print("insert book title >> ");
String title = in.nextLine();
boolean found = false;
for (Book b : book)
{
if (title.equals(b.getTitle()))
{
System.out.println(b.toString());
found = true;
break;
}
}
if (!found) System.out.println("no data");
}
You could do it java 8 way as well:
public static void main(String[] args) {
Book[] book = {new Book("java", 150, 2016), new Book("python", 100, 2019), new Book("javascript", 200, 2018)};
Scanner in = new Scanner(System.in);
System.out.print("insert book title >> ");
String title = in.nextLine();
Book b = Arrays.stream(book).filter(book1 -> book1.getTitle().equals(title)).findAny().orElse(null);
if (null == b) {
System.out.println("no data");
} else {
System.out.println(b);
}
}
I'd like to print out that I can't find the books that are not in the array, although I want just one sentence "no data".
Please give me some advice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.