1-7编程练习
public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
System.out.println("图书价格最低10元");
Book b = new Book();
b.content("红楼梦","曹雪芹","人民文学出版社",2);
b.Equal();
b.content("小李飞刀","古龙","中国长安出版社",55.5);
}
}public class Book {
//私有属性:书名、作者、出版社、价格
private String title; //书名
private String author; //作者
private String press; //出版社
private double price; //价格
//通过构造方法实现属性赋值
public void Equal(){
System.out.println("=================");
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String getTitle() {
System.out.println("书名:"+this.title);
return title;
}
public String getAuthor() {
System.out.println("作者:"+this.author);
return author;
}
public String getPress() {
System.out.println("出版社:"+press);
return press;
}
public void setPress(String press) {
}
public double getPrice() {
if(price<=10){
System.out.println("图书价格必须大于10!");
System.out.println("价格:"+10);
}else{
System.out.println("价格:"+price);
}
return price;
}
public void setPrice(double price) {
}
//信息介绍方法,描述图书所有信息
public void content(String getTitle,String getAuthor,String getPress,double getPrice){
title = getTitle;
author = getAuthor;
press = getPress;
price = getPrice;
getTitle();
getAuthor();
getPress();
getPrice();
}
}老师你好,请问我这样写有什么需要注意的地方,另外是否还能怎样精简或优化?谢谢老师...
43
收起
正在回答
2回答
练习中的问题如下:
1、没有定义构造方法
2、get方法建议不写输出语句,可以将输出语句写到显示信息的方法中
3、对图书价格的限定应该放到setPrice方法中,也就是赋值的时候进行限定
4、书名和作者为只读属性,可以将书名和作者相关的set方法去掉
5、content()方法不必有参数,直接输出成员变量就可以
6、按照Java代码规范,方法名首字母应小写
建议再改改,如有问题再提问。祝学习愉快!
小终极
2018-02-12 22:17:37
public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
System.out.println("图书价格最低10元");
Book b = new Book();
b.Book("红楼梦","曹雪芹","人民文学出版社");
b.setPrice(6);
b.content();
b.equal();
b.Book("小李飞刀","古龙","中国长安出版社");
b.setPrice(55.5);
b.content();
}
}public class Book {
//私有属性:书名、作者、出版社、价格
private String title,author,press; //书名
private double price; //价格
//通过构造方法实现属性赋值
public void Book(String title,String author,String press) {
this.title = title;
this.author = author;
this.press = press;
}
public void equal(){
System.out.println("=================");
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPress() {
return press;
}
public void setPress(String press) {
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if(price<=10){
this.price = 10;
System.out.println("价格必须大于10!已为您修改价格为10元.");
}else{
this.price = price;
}
}
//信息介绍方法,描述图书所有信息
public void content() {
System.out.println("书名:"+getTitle());
System.out.println("作者:"+getPress());
System.out.println("出版社:"+getPress());
System.out.println("价格:"+getPrice());
}
}改
Android零基础入门2018版
- 参与学习 人
- 提交作业 5461 份
- 解答问题 7235 个
此次推出的专题为Android攻城狮培养计划的第一部分语法与界面基础篇,将带大家从0开始学习Android开发。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星