pta-6-2 Book类的设计

阅读测试程序,设计一个Book类。

函数接口定义:

class Book{}

该类有 四个私有属性 分别是 书籍名称价格作者出版年份,以及相应的set 与get方法;该类有一个含有四个参数的构造方法,这四个参数依次是书籍名称价格作者出版年份

裁判测试程序样例:


import java.util.*;
public class Main {
    public static void main(String[] args) {
        List <Book>books=new ArrayList<Book>();
        Scanner in=new Scanner(System.in);
        for(int i=0;i<5;i++)
        {    String str=in.nextLine();
            String []data=str.split(",");
            Book book=new Book(data[0],Integer.parseInt(data[1]),data[2],Integer.parseInt(data[3]));
            books.add(book);
        }
        
        System.out.println(totalprice(books));    
    }
    
    /*计算所有book的总价*/
    public static int totalprice(List <Book>books) 
    {  int result=0;
        for(int i=0;i<books.size();i++){result+=books.get(i).getPrice();}
        return result;
    }
}

/* 请在这里填写答案 */

输入样例:

三体,100,无名氏,1998
上下五千年,50,编辑部,2015
海底世界,50,无名氏2,2000
三体1,100,无名氏3,2017
三体3,100,无名氏4,1998

输出样例:

400

正确答案:

class Book {
    // 私有属性
    private String title;
    private int price;
    private String author;
    private int publishYear;

    // 含有四个参数的构造方法
    public Book(String title, int price, String author, int publishYear) {
        this.title = title;
        this.price = price;
        this.author = author;
        this.publishYear = publishYear;
    }

    // getter 和 setter 方法
    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    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;
    }

    public int getPublishYear() {
        return publishYear;
    }

    public void setPublishYear(int publishYear) {
        this.publishYear = publishYear;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值