请查看一下代码,是否有优化空间

来源:1-7 编程练习

henghu

2019-06-07 22:39:23

public class Book {
	// 私有属性:书名、作者、出版社、价格
	private String bookname;
	private String author;
	private String press;
	private double price;

	// 通过构造方法实现属性赋值
	public Book(String bookname, String author, String press, double price) {
		this.bookname = bookname;
		this.author = author;
		setPress(press);
		setPrice(price);
	}

	/*
	 * 通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
	 * 2、限定作者、书名均为只读属性
	 */
	public String getBookname() {
		return this.bookname;
	}

	public String getAuthor() {
		return this.author;
	}

	public void setPress(String press) {
		this.press = press;
	}

	public String getPress() {
		return this.press;
	}

	public void setPrice(double price) {
		if (price < 10) {
			System.out.println("你输入的价格无效,价格必须大于10元");
			this.price = 10;
		} else {
			this.price = price;
		}

	}

	public double getPrice() {
		return this.price;
	}
	// 信息介绍方法,描述图书所有信息

	Book(String bookname) {

		System.out.println("图书价格最低10元");
		System.out.println("书名:" + getBookname());
		System.out.println("书名:" + getBookname());
		// this.print();
	}

	public void print() {
		System.out.println("书名:" + getBookname());
		System.out.println("作者:" + getAuthor());
		System.out.println("出版社:" + getPress() + "元");
		System.out.println("价格:" + getPrice() + "元");

	}
}

public class BookTest {
	// 测试方法
	public static void main(String[] args) {
		// 实例化对象,调用相关方法实现运行效果
		System.out.println("图书价格最低10元");
		Book one = new Book("红楼梦", "曹雪芹", "人民文学出版社", -10);
		one.print();
		System.out.println("===========================");
		Book two = new Book("小李飞刀", "古龙", "中国长安出版社", 55.5);
		two.print();

	}

}
写回答

2回答

好帮手慕小班

2019-06-09

同学你好,根据贴出代码,有如下的一些修改和优化建议:

1、Book(String bookname){}-->这是另一个构造方法吗

http://img.mukewang.com/climg/5cfc65e5000175ff09370521.jpg

这个方法并没有使用,所以这里可以去掉!

2、这个图书的最低价格的输出语句就在set的方法中,所以在测试类中的输出语句可以不写哦

http://img.mukewang.com/climg/5cfc66b90001800907850294.jpg

剩下的的代码符合题目要求,符合本小节中封装的要求哦!

如果我的回答解决了你的问题,请采纳。祝学习愉快。

0

henghu

提问者

2019-06-07


Book(String bookname) {

 

        System.out.println("图书价格最低10元");

        System.out.println("书名:" + getBookname());

        System.out.println("书名:" + getBookname());

        // this.print();

    }

 

    public void print() {

        System.out.println("书名:" + getBookname());

        System.out.println("作者:" + getAuthor());

        System.out.println("出版社:" + getPress() + "元");

        System.out.println("价格:" + getPrice() + "元");

 

    }

这几个是多写的,需要删除掉

0

0 学习 · 11489 问题

查看课程