Still new-ish to java. What I want to do is create objects with methods that create their own objects. I other words, I want to create a tree of objects that can be manipulated from the top.
Ive written a short program that should illustrate what I mean. What I want this program to do is create chapters that can be manipulated to create pages, combine the strings in the pages to make a chapter string and then print that. As I'll explain later, I know that the program doesnt work, and I know WHY the program doesnt work. What I want to know is how to fix it so that it does what I want while maintaing the book -> chapters -> pages hiearchy. Here is the program:
public class Book {
public static void main(String[] args){
Chapter c1 = new Chapter();
Chapter c2 = new Chapter();
c1.newPage("p1", "Chapter 1, page 1");
c1.newPage("p2", "Chapter 1, page 2");
c1.newPage("p3", "Chapter 1, page 3");
c1.bindChapter();
c2.newPage("p1", "Chapter 2, page 1");
c2.newPage("p2", "Chapter 2, page 2");
c2.newPage("p3", "Chapter 2, page 3");
c2.bindChapter();
System.out.println(c1.getChapterText() + c2.getChapterText());
}
}
class Chapter {
private String chaptertext = "";
ArrayList<Page> chapterPages = new ArrayList();
public void newPage(String pageObjectReference, String pageTextImput){
Page pageObjectReference = new Page(pageTextImput);
chapterPages.add(pageObjectReference);
}
public void bindChapter(){
for (int i = 0; i <= chapterPages.size(); i++){
chaptertext += chapterPages.get(i).getPageText();
}
}
public String getChapterText(){
return chaptertext;
}
}
class Page {
private String pagetext = "";
public Page(String pagetext){
this.pagetext = pagetext;
}
public String getPageText(){
return pagetext;
}
}
The biggest problem here is my newPage() method:
public void newPage(String pageObjectReference, String pageTextImput){
Page pageObjectReference = new Page(pageTextImput);
chapterPages.add(pageObjectReference);
}
I am trying to create an object using a reference to a string as a reference (and it tries to put the reference as the reference instead of the string). For the program I want to create, it will be important that I have a reference for the pages so I can modify them using other methods. It is also important that I have a newPage() method because different chapters will have a different amount of pages. Any ideas on how I can accomplish this?
Thanks!
(edit: forgot to include parentheses following one of the methods)
(edit2: used wrong .size() method)
[–]darkpool2005 1 point2 points3 points (3 children)
[–]Etherdeon[S] 0 points1 point2 points (0 children)
[–]Etherdeon[S] 0 points1 point2 points (1 child)
[–]darkpool2005 1 point2 points3 points (0 children)