英文:
[JAVA]How can I add here this array code?
问题
我想打印出在数组中找不到的书籍,尽管我只想要一句话:“没有数据”。
请给我一些建议。
英文:
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.
答案1
得分: 1
你可以添加一个布尔变量,在找到书籍后进行更新,一旦从循环中退出,如果未找到该书,它将打印 'no data',类似于这样:
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("插入书籍标题 >> ");
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("无数据");
}
英文:
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");
}
答案2
得分: 1
你也可以使用Java 8的方法来实现:
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("插入书名 >> ");
String title = in.nextLine();
Book b = Arrays.stream(book).filter(book1 -> book1.getTitle().equals(title)).findAny().orElse(null);
if (null == b) {
System.out.println("没有数据");
} else {
System.out.println(b);
}
}
英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论