用java实现一个枚举类,通过编号(从1开始)得到30本世界名著
时间: 2023-05-27 17:05:44 浏览: 127
这里给出一个简单的例子:
```java
public enum WorldFamousBooks {
BOOK1("The Catcher in the Rye", "J.D. Salinger"),
BOOK2("1984", "George Orwell"),
BOOK3("To Kill a Mockingbird", "Harper Lee"),
BOOK4("The Great Gatsby", "F. Scott Fitzgerald"),
BOOK5("One Hundred Years of Solitude", "Gabriel Garcia Marquez"),
// ... 省略其余25本书
private final String name;
private final String author;
WorldFamousBooks(String name, String author) {
this.name = name;
this.author = author;
}
public String getName() {
return name;
}
public String getAuthor() {
return author;
}
public static WorldFamousBooks getByIndex(int index) {
if (index < 1 || index > 30) {
throw new IllegalArgumentException("Invalid index: " + index);
}
return values()[index - 1];
}
}
```
使用方式:
```java
WorldFamousBooks book = WorldFamousBooks.getByIndex(1);
System.out.println(book.getName() + " by " + book.getAuthor());
```
输出:
```
The Catcher in the Rye by J.D. Salinger
```
阅读全文