无法实现“图书价格必须大于10,如果无效需进行提示,并强制赋值为10”,代码哪里需要优化?

无法实现“图书价格必须大于10,如果无效需进行提示,并强制赋值为10”,代码哪里需要优化?

Book.java

public class Book {
//私有属性:书名、作者、出版社、价格
private String bookName;
private String author;
private String print;
private double price;
//通过构造方法实现属性赋值
public Book(String bookName,String author,String print,double price) {
this.bookName=bookName;
this.author=author;
this.print=print;
this.price=price;

}

/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String getPrint() {
return print;
}
public void setPrint(String print) {
this.print = print;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if(price<10) {
System.out.println("图书价格必须大于10");
price=10;
}else {
this.price = price;
}
}
public String getBookName() {
return bookName;
}
public String getAuthor() {
return author;
}
//信息介绍方法,描述图书所有信息
public void info() {
System.out.println("书名:"+this.getBookName());
System.out.println("作者:"+this.getAuthor());
System.out.println("出版社:"+this.getPrint());
System.out.println("价格:"+this.getPrice());
}

}

BookTest.java

public class BookTest {

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


正在回答

登陆购买课程后可参与讨论,去登陆

2回答

同学你好,在有参构造方法中,要调用set属性名()才可以,修改代码如下所示:

https://img1.sycdn.imooc.com//climg/61317e730911d78008320220.jpg

https://img1.sycdn.imooc.com//climg/61317e8409f85f6b04960317.jpg

祝学习愉快~

浩淼6924806 2021-09-03 08:30:09
public void setPrice(double price) {
if(price<10) {
System.out.println("图书价格必须大于10");
price=10;
}else {
this.price = price;
}
}

这个位置优化一下

public void setPrice(double price){

if(price>=10){

this.price=price;

System.out.println("图书的价格为"+price);

}else {

System.out.println("图书的价格必须大于10元")

this.price=10;

}

}

  • 提问者 lgk0591 #1

    经测试,仍然无法实现。

    2021-09-03 09:26:40
  • 慕村2333636 回复 提问者 lgk0591 #2
    你好!可以再试试优化下面代码,应该就可以了。

    public class BookTest {

    // 测试方法
    public static void main(String[] args) {
    //实例化对象,调用相关方法实现运行效果
    Book one=new Book("红楼梦","雪芹","人民文学出版社",12);
    Book two=new Book("小李飞刀","古龙","中国长安出版社",55.5);
    ​one.setPrice(8);//价格小于10,强制赋值为10元(这里优化一下)
    one.info();
    System.out.println("==============================");
    two.info();
    }
    }


    2021-10-08 02:39:17
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师