3.java定义一个能输出书名、作者、出版社和价格等信息的图书类,存放于包net.book下。然后再编写一个存放于包com.test下的测试类,类中定义一个一维图书对象数组,用于存放6本图书,然后使用增强for语句显示所有的图书信息。用三种简单方法
时间: 2024-05-05 22:22:13 浏览: 133
方法一:
net.book.Book类代码:
```java
package net.book;
public class Book {
private String title;
private String author;
private String publisher;
private double price;
public Book(String title, String author, String publisher, double price) {
this.title = title;
this.author = author;
this.publisher = publisher;
this.price = price;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getPublisher() {
return publisher;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", publisher='" + publisher + '\'' +
", price=" + price +
'}';
}
}
```
com.test.Test类代码:
```java
package com.test;
import net.book.Book;
public class Test {
public static void main(String[] args) {
Book[] books = new Book[6];
books[0] = new Book("Java编程思想", "Bruce Eckel", "机械工业出版社", 89.00);
books[1] = new Book("深入浅出设计模式", "程杰", "电子工业出版社", 49.00);
books[2] = new Book("Effective Java", "Joshua Bloch", "机械工业出版社", 79.00);
books[3] = new Book("Java核心技术-卷1", "Cay S. Horstmann", "机械工业出版社", 109.00);
books[4] = new Book("Java 8实战", "Raoul-Gabriel Urma", "人民邮电出版社", 89.00);
books[5] = new Book("Head First设计模式", "Eric Freeman", "中国电力出版社", 69.00);
// 方法一:使用普通for循环遍历
for (int i = 0; i < books.length; i++) {
System.out.println(books[i]);
}
}
}
```
方法二:
com.test.Test类代码:
```java
package com.test;
import net.book.Book;
public class Test {
public static void main(String[] args) {
Book[] books = new Book[6];
books[0] = new Book("Java编程思想", "Bruce Eckel", "机械工业出版社", 89.00);
books[1] = new Book("深入浅出设计模式", "程杰", "电子工业出版社", 49.00);
books[2] = new Book("Effective Java", "Joshua Bloch", "机械工业出版社", 79.00);
books[3] = new Book("Java核心技术-卷1", "Cay S. Horstmann", "机械工业出版社", 109.00);
books[4] = new Book("Java 8实战", "Raoul-Gabriel Urma", "人民邮电出版社", 89.00);
books[5] = new Book("Head First设计模式", "Eric Freeman", "中国电力出版社", 69.00);
// 方法二:使用增强for循环遍历
for (Book book : books) {
System.out.println(book);
}
}
}
```
方法三:
com.test.Test类代码:
```java
package com.test;
import net.book.Book;
public class Test {
public static void main(String[] args) {
Book[] books = new Book[6];
books[0] = new Book("Java编程思想", "Bruce Eckel", "机械工业出版社", 89.00);
books[1] = new Book("深入浅出设计模式", "程杰", "电子工业出版社", 49.00);
books[2] = new Book("Effective Java", "Joshua Bloch", "机械工业出版社", 79.00);
books[3] = new Book("Java核心技术-卷1", "Cay S. Horstmann", "机械工业出版社", 109.00);
books[4] = new Book("Java 8实战", "Raoul-Gabriel Urma", "人民邮电出版社", 89.00);
books[5] = new Book("Head First设计模式", "Eric Freeman", "中国电力出版社", 69.00);
// 方法三:使用Lambda表达式遍历
java.util.Arrays.stream(books).forEach(System.out::println);
}
}
```
阅读全文