gpt4 book ai didi

java - 如何从另一个类的数组中打印特定行

转载 作者:行者123 更新时间:2023-12-02 11:16:53 24 4
gpt4 key购买 nike

所以我试图只打印添加到数组中的小说,但我不知道如何..我还需要返回特定种类的书籍数量。我是编程新手,所以请放轻松:)

这是应用程序,我必须从控制台添加所有书籍从控制台添加的每个单词都会触发一个特定的操作,因此要打印书籍,我需要编写 print ,要添加我需要编写 add 、书籍类型、书名、作者等。

import java.util.*;
public class App{
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Library bib = Library.getInstance();
String line = "";
line = s.nextLine();
String[] v = line.split("\\s+");
while(true){
switch(v[0]){
case "add":
String title = v[2];
String autor = v[3];
Book c = null;
if("story".equals(v[1])){
c = new Story(title, autor);
} else if("novel".equals(v[1])){
int pages = Integer.parseInt(v[4]);
c = new Novel(title, autor, pages);
} else if("poetry".equals(v[1])){
String publish = v[4];
c = new Poetry(title, autor, publish);
}
bib.adauga(c);
break;
case "print" :
case "return" :
case "exit" : System.exit(0); break;
default : System.out.println("Command " + v[0] + " does not exist");
}
}
}
}
<小时/>
import java.util.*;
public class Library{
private static Library instance;
List<Book> books;

private Library(){
books = new ArrayList<>();
}

public static Library getInstance(){
if(instance == null){
instance = new Library();
}
return instance;
}

public void adauga(Book c){
books.add(c);

}

public void afisare(){
for(Book c : books){
System.out.println(c);
}
}


}
<小时/>
public abstract class Book{
String title;
String autor;

public Book(String title, String autor){
this.title=title;
this.autor=autor;
}

@Override
public String toString(){
return title + " " + autor;
}
}
<小时/>
public class Novel extends Book {
int pages;

public Novel(String title, String autor, int pages){
super(title, autor);
this.pages=pages;
}

@Override
public String toString(){
return super.toString() + " " + pages;
}
}

最佳答案

您可以使用instanceof来检查对象的类型。

//Go through every book
for(Book book : bib.books){
if(book instanceof Novel){
System.out.println(book);
}
}

关于java - 如何从另一个类的数组中打印特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203929/

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