老师帮忙看看,为啥运行错误,还有代码中的书写错误。

来源:1-9 编程练习

慕用4915122

2020-11-02 18:47:58

public class Book {

  //私有属性:书名、作者、出版社、价格

     private String book;

     private String name;

     private String company;

     private double money;

     

  //通过构造方法实现属性赋值

public Book(String book,String name,String company,double money){

    this.book=book;

    this.name=name;

    this.company=company;

   setMoney(money);

}

    /*通过公有的get/set方法实现属性的访问,其中:

    1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10

    2、限定作者、书名均为只读属性

    */

public String getBook(String book){

    return this.book;

}

public String getName(String name){

    return this.name;

}

public void setCompany(String company){

    this.company=company;

}

public String getCompany(String company){

    return this.company=company;

}

public void setMoney(double money){

    if(money>10){

    this.money=money;

    }else{

    this.money=10;

    System.out.println("图书价格为最低10元"+money);

    }    

        

}

public double getMoney(double money){

    return this.money=money;

}

  //信息介绍方法,描述图书所有信息

public void info(){

        System.out.println("书名:" + this.getBook());

        System.out.println("作者:" + this.getName());

        System.out.println("出版社:" + this.getCompany());

        System.out.println("价格:" + this.getMoney() + "元");


}

}

public class BookTest {


     // 测试方法

public static void main(String[] args) {

      //实例化对象,调用相关方法实现运行效果

        Book b1 = new Book("红楼梦", "曹雪芹", "人民文学出版社", 10);

        Book b2 = new Book("小李飞刀", "古龙", "中国长安出版社", 55.5);

        

        b1.info();

        System.out.println("===============================");

        b2.info();

    }

}


写回答

1回答

好帮手慕小尤

2020-11-02

同学你好,1.在info()方法中调用未定义的方法,导致出现异常。如下图所示:

http://img.mukewang.com/climg/5f9fe6040925fcac04570221.jpg

http://img.mukewang.com/climg/5f9fe62709f215ea05410371.jpg

2.  get方法不需要赋值与参数,直接返回当前类的属性值即可。修改后代码如下所示:

http://img.mukewang.com/climg/5f9fe537096620fa04550425.jpg

public class Book {
//私有属性:书名、作者、出版社、价格
private String book;
private String name;
private String company;
private double money;

//通过构造方法实现属性赋值
public Book(String book,String name,String company,double money){
this.book=book;
this.name=name;
this.company=company;
setMoney(money);
}
/*通过公有的get/set方法实现属性的访问,其中:
1、限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
2、限定作者、书名均为只读属性
*/
public String getBook() {
return book;
}

public String getName() {
return name;
}

public String getCompany() {
return company;
}

public double getMoney() {
return money;
}
public void setCompany(String company){
this.company=company;
}
public void setMoney(double money){
if(money>10){
this.money=money;
}else{
this.money=10;
System.out.println("图书价格为最低10元"+money);
}

}
//信息介绍方法,描述图书所有信息
public void info(){
System.out.println("书名:" + this.getBook());
System.out.println("作者:" + this.getName());
System.out.println("出版社:" + this.getCompany());
System.out.println("价格:" + this.getMoney() + "元");
}
}


0

0 学习 · 16556 问题

查看课程