怎么修改才能达成需要的效果
public class Book {
//私有属性:书名、作者、出版社、价格
private String title;
private String author;
private String press;
private double price;
//通过构造方法实现属性赋值
public Book(String title,String author,String press,double price){
this.title=title;
this.author=author;
this.press=press;
this.price=price;
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String gettitle(){
return title;
}
public String getauthor(){
return author;
}
public String getpress(){
return press;
}
public void setpress(){
this.press=press;
}
public double getprice(){
return price;
}
public void setprice(double price){
if(price>10){
this.price=price;
}else{
System.out.println("图书价格必须大于10");
this.price=10;
}
}
//信息介绍方法,描述图书所有信息
public void show(){
System.out.println("书名:"+title);
System.out.println("作者:"+author);
System.out.println("出版社:"+press);
System.out.println("价格:"+price+"元");
}
}public class BookTest {
// 测试方法
public static void main(String[] args) {
//实例化对象,调用相关方法实现运行效果
Book one=new Book("红楼梦","曹雪芹","人民文学出版社",8);
Book two=new Book("小李飞刀","古龙","中国长安出版社",55.5);
one.show();
System.out.println("===================================");
two.show();
}
}
10
收起
正在回答
1回答
同学你好,同学的代码中存在以下问题:
1.由于同学的Book类的有参构造中使用的this属性形式,没有使用到set方法,所以无法对price属性进行限制。建议构造方法中使用set方法进行赋值。
2.set和get方法的命名不规范,应当在第二个单词开始,每个单词的首字母大写,例如gettitle应当为getTitle。
3.setpress方法应当有参数,用于对属性进行赋值。
4.title和author属性没有对应的set方法。
修改后的代码如下:
public class Book {
// 私有属性:书名、作者、出版社、价格
private String title;
private String author;
private String press;
private double price;
// 通过构造方法实现属性赋值
public Book(String title, String author, String press, double price) {
this.setTitile(title);
this.setAuthor(author);
this.setPress(press);
this.setPrice(price);
}
/*
* 通过公有的get/set方法实现属性的访问,其中: 1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10 2、限定作者、书名均为只读属性
*/
public String getTitle() {
return title;
}
public void setTitile(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
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) {
this.price = price;
} else {
System.out.println("图书价格必须大于10");
this.price = 10;
}
}
// 信息介绍方法,描述图书所有信息
public void show() {
System.out.println("书名:" + title);
System.out.println("作者:" + author);
System.out.println("出版社:" + press);
System.out.println("价格:" + price + "元");
}
}祝学习愉快~
2023版Java工程师
- 参与学习 人
- 提交作业 8788 份
- 解答问题 9886 个
综合就业常年第一,编程排行常年霸榜,北上广深月薪过万! 不需要基础,无需脱产即可学习,只要你有梦想,想高薪! 全新升级:技术栈升级(包含VUE3.0,ES6,Git)+项目升级(前后端联调与功能升级)
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星