Javase的小练习!!!

KIM·JAE HWAN 2021-04-10 03:35:25
求解 封装和集合的问题
...全文
134 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
netwar 2021-04-11
  • 打赏
  • 举报
回复

import java.util.*;

public class Hello {
    public static void main(String[] args) {
        // phase 2
        final int total = 3;
        final Random random = new Random();
        List<Book> books = new ArrayList<>(total);
        try (Scanner sc = new Scanner(System.in)) {
            for (int i = 1; i <= total; i++) {
                var book = new Book();
                book.setCode("code" + i);
                book.setName("name" + i);
                book.setPrice(random.nextDouble() * 1000);
                books.add(book);
            }
        }

        // phase 3
        for (var book : books) {
            System.out.println(book);
        }
    }
}

// Phase 1
class Book {
    private String code;
    private String name;
    private Double price;

    @Override
    public String toString() {
        String format = String.format("code=%s,name=%s,price=%f", this.code, this.name, this.price);
        return format;
    }

    public String getCode() {
        return code;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setCode(String code) {
        this.code = code;
    }

}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧