Java编写,创建图书类:Book 2、定义私有属性:name书名,price价格,author作者,country出厂国籍,type类型 3、属性的约束如下: name:长度不能超过20个字符 price:30至300之间 country:只能是中国或美国或日本 type:不能为'黄色类',其它都可以 4、创建getString方法,返回基本信息:书名:xxx,价格:xxx,作者:xxx,出厂国籍:xxx,类型:xxx 5、创建测试类,在Main方法中创建图书对象为其属性赋值再打印其基本信息
时间: 2023-05-30 19:02:59 浏览: 944
book(IoC).zip_java 编写book类
5星 · 资源好评率100%
1. Book.java
public class Book {
private String name;
private double price;
private String author;
private String country;
private String type;
public Book(String name, double price, String author, String country, String type) {
this.name = name;
this.price = price;
this.author = author;
this.country = country;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
if (name.length() > 20) {
System.out.println("书名长度不能超过20个字符");
return;
}
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if (price < 30 || price > 300) {
System.out.println("价格必须在30至300之间");
return;
}
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
if (!country.equals("中国") && !country.equals("美国") && !country.equals("日本")) {
System.out.println("出厂国籍只能是中国或美国或日本");
return;
}
this.country = country;
}
public String getType() {
return type;
}
public void setType(String type) {
if (type.equals("黄色类")) {
System.out.println("类型不能为'黄色类'");
return;
}
this.type = type;
}
public String getString() {
return "书名:" + name + ",价格:" + price + ",作者:" + author + ",出厂国籍:" + country + ",类型:" + type;
}
}
2. Test.java
public class Test {
public static void main(String[] args) {
Book book = new Book("Java编程思想", 99.9, "Bruce Eckel", "美国", "计算机类");
System.out.println(book.getString());
book.setName("Java核心技术");
book.setPrice(199.9);
book.setCountry("中国");
book.setType("计算机类");
System.out.println(book.getString());
}
}
输出结果:
书名:Java编程思想,价格:99.9,作者:Bruce Eckel,出厂国籍:美国,类型:计算机类
书名:Java核心技术,价格:199.9,作者:Bruce Eckel,出厂国籍:中国,类型:计算机类
阅读全文