java - What is the difference between the two marked methods? Are their outputs the same? -
this code questioned in exercise had solve. although code shows right result (version one), i'm not sure if solution provided (version two) or if correct @ all. task write class representing book , methods page forward , backward using self-references.
public class book { private int page; private book nextpage; public book(int page) { setpage(page); setnextpage(null); } //getter , 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 getting 2 int values , 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 = currentpage; <= 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 simple , shows execution of methods:
public class bookdemo { public static void main(string[] args) { book.pagebackward1(500, 455); system.out.println(); book.pagebackward2(500, 455); } }
the solutions, you've said, equivalent (literally! upon same input data output same data, despite through stdout instead of return value).
i believe due supplied solution exercise's proposal pre-fill/pre-generate book
s before stepping through them using getnextpage()
getter. believe you've reached same conclusion since did same thing in different order, stepping through instances once create them (as opposed to, example, stepping through of existing books
arrive @ final 1 before creating next).
in opinion exercise fails teach due these wonky semantics , unclear goals, , more productive students start working straight out more explicitly named , generic linked list data structures.
Comments
Post a Comment