我正在尝试创建一个将书名,页数和出版年份作为用户输入的程序。当用户未在名称字段中输入任何内容时,程序应询问用户将要打印的内容:仅书籍名称或用户提供的所有信息。这是我的主要代码:
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:
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语句为止。如何仅打印对象的第一个元素(书名)?提前致谢。
问题来源:stackoverflow
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;
}
public String getName(){
return name;
}
}
然后调用book.getName()即可获取书名,现在只需编写一个循环即可显示每本书的名称
答案来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。