为什么我价格里面的if没有运行
package com.imooc.animal;
public class Book {
// 私有属性:书名、作者、出版社、价格
private String name;
private String author;
private String comoany;
private double price;
// 通过构造方法给属性赋值
public Book(String name, String author) {
this.name = name;
this.author = author;
}
/*
* 通过公有的get/set实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性
*/
public String getComoany() {
return comoany;
}
public void setComoany(String comoany) {
this.comoany = comoany;
}
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 getName() {
return name;
}
public String getAuthor() {
return author;
}
// 信息介绍方法,描述图书所有信息
public String info() {
String st = "书名:" + this.getName() + "\n作者:" + this.getAuthor() + "\n出版社:" + this.getComoany() + "\n价格"
+ this.getPrice();
return st;
}
}
package com.imooc.animal;
public class BookTest {
public static void main(String[] args) {
Book book = new Book("红楼梦", "曹雪芹");
book.setComoany("人民文学出版社");
book.setPrice(9);
System.out.println(book.info());
System.out.println("=====================");
Book book1 = new Book("小李飞刀", "古龙");
book1.setComoany("中国长安出版社");
book1.setPrice(55.5);
System.out.println(book1.info());
}
}
正在回答 回答被采纳积分+1
同学你好,测试了同学修改后的代码,“图书最低价格为10!”这条语句已经输出了

建议同学重新运行一下,以下附上老师修改后的代码,同学可对比看一下:
public class Book {
// 私有属性:书名、作者、出版社、价格
private String name;
private String author;
private String comoany;
private double price = 2;
// 通过构造方法给属性赋值
public Book(String name, String author) {
this.name = name;
this.author = author;
}
/*
*
* 通过公有的get/set实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性
*
*/
public String getComoany() {
return comoany;
}
public void setComoany(String comoany) {
this.comoany = comoany;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price < 10) {
System.out.println("图书最低价格为10!");
this.price = 10;
} else {
this.price = price;
}
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
// 信息介绍方法,描述图书所有信息
public String info() {
String st = "书名:" + this.getName() + "\n作者:" + this.getAuthor() + "\n出版社:" + this.getComoany() + "\n价格"
+ this.getPrice();
return st;
}
}public class BookTest {
public static void main(String[] args) {
Book book = new Book("红楼梦", "曹雪芹");
book.setComoany("人民文学出版社");
book.setPrice(9);
System.out.println(book.info());
System.out.println("=====================");
Book book1 = new Book("小李飞刀", "古龙");
book1.setComoany("中国长安出版社");
book1.setPrice(55.5);
System.out.println(book1.info());
}
}如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星