我正在为我在技术部门做的一门课程中的练习编写应用程序。它应该实例化 5 个类的对象Book
,其中包含书名、作者和页数的数据字段。我在使用for.. loop
. 在第一个循环之后,它每次都会跳过一个步骤,我不知道为什么。这是我的代码
import java.util.*;
public class LibraryBook2
{
public static void main(String[]args)
{
String name;
String author;
int pages;
Book[] novel = new Book[5];
novel[0] = new Book();
novel[1] = new Book();
novel[2] = new Book();
novel[3] = new Book();
novel[4] = new Book();
Scanner kb = new Scanner(System.in);
for (int i = 0; i< novel.length;)
{
System.out.println("Please Enter the books title");
name = kb.nextLine();
novel[i].setTitle(name);
System.out.println("Please enter the books author");
author = kb.nextLine();
novel[i].setAuthor(author);
System.out.println("Please enter the number of pages in this book");
pages = kb.nextInt();
novel[i].setPages(pages);
System.out.println(""+novel[i].title);
System.out.println(""+novel[i].author);
System.out.println(""+novel[i].pages);
++i;
}
for (int x = 0; x<novel.length; x++)
{
System.out.print(""+ novel[x].title + "\n" + novel[x].author + "\n" + novel[x].pages);
}
}
}
在第一个for
循环中,它循环一次,打印书名、作者和我输入的页数,就像它应该的那样。但第二次,它打印“请输入书名”,然后直接跳到第二次println
,无需等待输入。我是对象数组的新手,一般是java,所以任何帮助表示赞赏。提前致谢。