I am writing an application for an exercise in a course I am doing at tech. It is supposed to instantiate 5 objects of the class Book, which contains data fields for a book’s title, author and number of pages. I am having issues with a for.. loop. It skips a step every time after the first loop and I cannot figure out why. Here is my code
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);
}
}
}
During the first for loop, it loops once, prints the book’s title, author and number of pages I entered, like it should. But the second time, it prints “Please enter the books title” then skips straight to the second println without waiting for input. I am new to arrays of objects, and java in general, so any help is appreciated.
Thanks in advance.
change the code like this:
Read the page number as nextLine , instead of integer.