This code was questioned in an exercise I had to solve. Although my code shows the right result (version one), I'm not sure if it is as good as the solution provided (version two) or if it is correct at all. The task is to write a class which is representing a book and methods to page forward and backward using self-references.
public class Book {
private int page;
private Book nextPage;
public Book(int page) {
setPage(page);
setNextPage(null);
}
//Getter and Setter
public void setPage(int page){
this.page = page;
}
public int getPage() {
return this.page;
}
public void setNextPage(Book nextPage) {
this.nextPage = nextPage;
}
public Book getNextPage() {
return nextPage;
}
/*The following methods are getting two int values and should page backward, showing each page number. */
Version one:
public static void pageBackward1(int currentPage, int goalPage) {
Book page = new Book(currentPage);
System.out.print("Page " + page.getPage() + " ");
while(goalPage != page.getPage()) {
currentPage--;
page.nextPage = new Book(currentPage);
page = page.nextPage;
System.out.print("Page " + page.getPage() + " ");
}
}
Version two:
public static void pageBackward2(int currentPage, int goalPage) {
Book previousPage = null;
for(int i = currentPage; i <= goalPage; i++) {
Book page = new Book(i);
page.setNextPage(previousPage);
previousPage = page;
}
Book page = previousPage;
while(page != null) {
System.out.print("Page " + page.getPage() + " ");
page = page.getNextPage();
}
System.out.println();
}
}
The following demo-class is simple and shows the execution of the methods:
public class BookDemo {
public static void main(String[] args) {
Book.pageBackward1(500, 455);
System.out.println();
Book.pageBackward2(500, 455);
}
}