老师能帮我看一下吗,我这个价格出来一直是2.0,两个都是,我不知道为什么
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Book;
/**
*
* @author liyij
*/
public class Book {
//私有属性:书名,作者,出版商,价格
private String book_name;
private String author;
private String publis;
private float price;
//通过构造方法实现属性的赋值
public Book(String book_name, String author, String publis, float price) {
this.book_name = book_name;
this.author = author;
this.publis = publis;
this.price = price;
}
//通过公有的get/set方法实现属性的访问:
//1.限定图书价格必须大于10,如果无效需进行提示,并强制赋值为10
//2.限定作者,书名仅为只读属性
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublis() {
return publis;
}
public void setPublis(String publis) {
this.publis = publis;
}
public double getPrice() {
return price;
}
public void setPrice(float price) {
if (price <= 10) {
System.out.println("价格必须是大于10元!!");
this.price = 10;
} else {
this.price=price;
}
}
public void show() {
System.out.println("书名: " + this.book_name);
System.out.println("作者: " + this.author);
System.out.println("出版社: " + this.publis);
System.out.println("价格: " + this.price);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Book;
/**
*
* @author liyij
*/
public class BookTest {
public static void main(String[] args) {
Book book = new Book("红楼梦", "曹雪芹", "人民文学出版社", 2f);
book.show();
System.out.println("----------------------------");
Book book2 = new Book("小李飞刀", "古龙", "中国长安出版社", 55.5f);
book.show();
}
}
正在回答
你都是book在show,book2呢????
另外你写了setter方法,在构造方法里要用setter方法取代直接的赋值,才可以不然有什么用?
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星