描述类:
package ketang;
public class Book {
//定义图书类(Book),要求有属性name(书名),price(价格),author(作者),
private String name;
private int price;
private String author;
@Override
public String toString() {
return "Book{" +
"name='" + name + '\'' +
", price=" + price +
", author='" + author + '\'' +
'}';
}
public Book() {
}
public Book(String name, int price, String author) {
this.name = name;
this.price = price;
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
测试类:
package ketang;
import java.util.ArrayList;
import java.util.Scanner;
public class Test_A {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
//一个ArrayList集合,正确的定义泛型
ArrayList<Book> list = new ArrayList<>();
//在主方法中循环创建3本图书对象
for (int i = 0; i <3 ; i++) {
System.out.println("请录入第"+(i+1)+"本书的名字");
String name = sc.next();
System.out.println("请录入第"+(i+1)+"本书的价格");
int price = sc.nextInt();
System.out.println("请录入第"+(i+1)+"本书的作者");
String author = sc.next();
//将上面录入数据封装成Book对象
Book book = new Book(name,price,author);
list.add(book);
}
System.out.println("添加前");
findAll(list);
//调用添加方法
add(list);
System.out.println("添加后:");
//调用findAll
findAll(list);
}
//再定义一个查询所有的方法(findAll),在方法中遍历集合,将集合中的图书信息展示到控制台。
public static void findAll(ArrayList<Book> list){
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
//再定义一个添加图书的方法(add),方法中实现添加一本图书到集合中
//返回值类型 void 参数列表:ArrayList<Book> list
public static void add(ArrayList<Book> list){
System.out.println("请录入添加的图书名字");
String name = sc.next();
System.out.println("请录入添加的图书价格");
int price = sc.nextInt();
System.out.println("请录入添加的图书作者");
String author=sc.next();
Book b = new Book(name,price,author);
list.add(b);
}
}