【发布时间】:2020-03-22 14:55:27
【问题描述】:
我正在尝试创建一个程序,该程序将书名、页数和出版年份作为用户输入。当用户没有在名称字段中输入任何内容时,程序应该询问用户将打印什么:只有书籍的名称或用户提供的所有信息。这是我的主要代码:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int index = 0;
Scanner reader = new Scanner(System.in);
ArrayList<Books> book = new ArrayList<>();
while (true) {
System.out.println("Name of the book: ");
String name = reader.nextLine();
if (name.isEmpty()) {
break;
}
System.out.println("Number of pages: ");
int pages = Integer.parseInt(reader.nextLine());
System.out.println("Year: ");
int year = Integer.parseInt(reader.nextLine());
book.add(new Books(name,pages,year));
}
while (true) {
System.out.println("What do you want to print?");
String whatwillbeprinted = reader.nextLine();
if (whatwillbeprinted.equals("everything")) {
while(index < book.size()) {
System.out.println(book.get(index));
index++;
}
}
if (whatwillbeprinted.equals("names")) {
while(index < book.size()) {
// print only names of the books
}
}
}
}
}
这是我的 Java 类,名为 Books:
public class Books {
private String name;
private int pages;
private int year;
public Books(String name, int pages, int year) {
this.name = name;
this.pages = pages;
this.year = year;
}
@Override
public String toString() {
return this.name + ", " + this.pages + ", " + this.year;
}
}
在最后一个 while 语句之前,一切都正常运行。如何仅打印对象的第一个元素(书名)?提前致谢。
【问题讨论】:
-
提示:
Book是一个更好的名称,因为它代表一本书。并使用books作为数组名称,因为它包含多本书。