思路:根据题目一句一句编写,这样很容易就学会了,按照题目编号编写;
首先定义一个Book类,其次编写一个BookTest类:
public class Book {
private String title;
private Integer pageNum;
private String type;
public Book(String title, Integer pageNum) {
this.type = "计算机";
this.title = title;
this.pageNum = pageNum;
}
public Book(String title, Integer pageNum, String type) {
this.title = title;
this.pageNum = pageNum;
this.type = type;
}
public void detail() throws Exception {
if (pageNum < 200) {
throw new Exception("教材页数不能少于200页");
} else {
System.out.println(toString());
}
}
@Override
public String toString() {
return "教材信息:{" +
"名称: '" + title + '\'' +
", 页数: " + pageNum +
", 种类: '" + type + '\'' +
'}';
}
}
BookTest类:
public class BookTest {
public static void main(String[] args) throws Exception {
Book book = new Book("c语言程序设计",500);
book.detail();
Book book2 = new Book("会计学",400, "金融类");
book2.detail();
Book book3 = new Book("建筑设计",150, "建筑类");
book3.detail();
}
}
运行结果:
