限制价格必须为10的问题?为什么价格为9时也是正常输出的?
public class Book {
private String bookname;
private String auther;
private String press;
public String getBookname() {
return bookname;
}
public String getAuther() {
return auther;
}
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){
System.out.println("价格必须大于10");
this.price = 10;
}
this.price = price;
}
private double price;
public Book(String bookname,String auther,String press,Double price){
this.bookname = bookname;
this.auther = auther;
this.press = press;
this.price = price;
}
public void info(){
System.out.println("书名: "+bookname+'\n'+"作者: "+auther+'\n'+"出版社: "+press+'\n'+"价格: "+price);
}
}
ublic class BookTest {
public static void main(String[] args){
Book bb = new Book("红楼梦","曹雪芹","人民文学出版社",9.00);
bb.info();
System.out.println("=====================");
Book bb1 = new Book("小李飞刀","古龙","中国长安出版社",11.00);
bb1.info();
}
}
------------------------------------------------改过后的代码
public class Book {
private String bookname;
private String auther;
private String press;
private double price;
public Book(String bookname,String auther,String press,double price){
this.bookname = bookname;
this.auther = auther;
this.setPress(press);
this.setPrice(price);
}
//get和set方法
public String getBookname() {
return bookname;
}
public String getAuther() {
return auther;
}
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){
price=10.0;
}
this.price = price;
}
public void info(){
System.out.println("书名:"+bookname);
System.out.println("作者:"+auther);
System.out.println("出版社:"+press);
System.out.println("价格:"+price+"元");
}
}
public class BookTest {
public static void main(String[] args){
Book bb = new Book("红楼梦","曹雪芹","人名文学出版社",9.0);
Book bb1= new Book("小李飞刀","古龙","中国长安出版社",55.5);
bb.info();
System.out.println("=======================");
bb1.info();
}
}
正在回答
因为你的构造方法里面根本没有调用set()方法阿,所以set()方法里的限制条件根本没用到
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星