请问这个代码作业如何
来源:1-7 编程练习
M灬spirit
2019-09-25 16:40:20
public class Book { //私有属性:书名、作者、出版社、价格 private String bookName; private String writer; private String press; private double price; //通过构造方法实现属性赋值 public Book(String bookName,String writer,String press,double price) { this.bookName=bookName; this.writer=writer; this.setPress(press); this.setPrice(price); } /*通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性 */ public String getPress() { return press; } public void setPress(String press) { this.press = press; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getBookName() { return bookName; } public String getWriter() { return writer; } //信息介绍方法,描述图书所有信息 public String toString() { return "图书价格最低10元\n"+"书名:"+this.getBookName()+"\n作者:"+this.getWriter() +"\n出版社:"+this.getPress()+"\n价格:"+this.getPrice(); } } public class BookTest { public static void main(String[] args) { //实例化对象,调用相关方法实现运行效果 Book one=new Book("红楼梦","曹雪芹","人民文学出版社",10); Book two=new Book("小李飞刀","古龙","中国长安出版社",55.5); System.out.println(one); System.out.println("==================="); System.out.println(two); } }
1回答
同学你好,程序完成的很好,但是有一个小问题,根据题目要求,限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10。需要在setPrice中进行判断。因为在set方法中可以保证代码的一致性,代码的统一规范性。具体如下:
代码如下:
public class Book { // 私有属性:书名、作者、出版社、价格 private String bookName; private String writer; private String press; private double price; // 通过构造方法实现属性赋值 public Book(String bookName, String writer, String press, double price) { this.bookName = bookName; this.writer = writer; this.setPress(press); this.setPrice(price); } /* * 通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性 */ public String getPress() { return press; } public void setPress(String press) { this.press = press; } public double getPrice() { return price; } public void setPrice(double price) { if (price < 10) { this.price = 10; } else { this.price = price; } } public String getBookName() { return bookName; } public String getWriter() { return writer; } // 信息介绍方法,描述图书所有信息 public String toString() { return "图书价格最低10元\n" + "书名:" + this.getBookName() + "\n作者:" + this.getWriter() + "\n出版社:" + this.getPress() + "\n价格:" + this.getPrice(); } }
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题