方法链接在具有数组的合成模型中打印

时间:2012-05-11 21:21:36

标签: java bluej

我是一名学生正在开发一个项目,该项目使用数组创建类来构建模型。我假设我到目前为止一切正常,但似乎我在驱动程序类中遇到了print语句的问题。我不确定它是否是我将方法链接在一起的方法。任何信息都会感激不尽。

public class MyWord
{
  private String word;     
  public MyWord(){
    word = "Null"; 
  }
  public MyWord(String s){
    word = s; 
  }
  public String getWord(){
    return word; 
  }
  public void setWord(String w){
    word = w; 
  }
  public void print(){
    System.out.println(word); 
  }
}

public class Page
{
private MyWord[] words = new MyWord[5]; 
private int pageNumber;     
public Page(){
    MyWord words[] = {} ; 
    pageNumber = 0; 
}    
public Page(MyWord[] a, int b){
    words = a; 
    pageNumber = b; 
}    
public MyWord[] getWord(){
    return words;
}   
public int getPageNumber(){
    return pageNumber;
}    
public void setMyWord(MyWord[] a){
    words = a; 
}    
public void setPageNumber(int b){
    pageNumber = b; 
}    
public void print(){
    System.out.print(" Page Number: " + pageNumber + " " + words);
}
}

public class Book
{
private Page[] p = new Page[5]; 
private String title;     
public Book(){
    Page[] p = {}; 
    title = " ";
}
    public Book(Page[] pa, String ti){
    p = pa; 
    title = ti; 
}
    public Page[] getPage(){
    return p; 
}
    public String getTitle(){
      return title; 
}    
public void setPage(Page[] x){
    p = x; 
}
public void setTitle(String y){
    title = y; 
}    
public void print(){
    System.out.print("Book info:" + p + " " + title);
}
}

public class Series
{
private Book bookOne, bookTwo, bookThree; 
private double price; 

public Series(){
    bookOne = null; 
    bookTwo = null; 
    bookThree = null; 
    price = 0; 
}

public Series(Book one, Book two, Book three, double p){
    bookOne = one; 
    bookTwo = two; 
    bookThree = three; 
    price = p; 
}    
public Book getBookTwo(){
    return bookTwo;
}    
public Book getBookOne(){
    return bookOne;
}    
public Book getBookThree(){
    return bookThree;
}    
public double getPrice(){
    return price;
}
public void setBookOne(Book bookOne){
    this.bookOne = bookOne;
}   
public void setBookTwo(Book bookTwo){
    this.bookTwo = bookTwo;
}    
public void setBookThree(Book bookThree){
    this.bookThree = bookThree;
}    
public void setPrice(double price){
    this.price = price; 
}
public void print(){
    System.out.println("Series info");
    System.out.println("Book one:" + bookOne + " Book Two: " +bookTwo
    + " Book Three: " + bookThree + "Price: " + price);
  }
 }

public class Driver
{
public static void main(String args[]){    
    MyWord[] w1 = new MyWord[2];
    w1[0] = new MyWord("Hello"); 
    w1[1] = new MyWord("Hola"); 

    Page[] p = new Page[2];
    p[0] = new Page(w1, 20); 
    p.print(); 
   }
}

1 个答案:

答案 0 :(得分:1)

p属于Page[]类型,即" Page"数组。并且数组没有print()方法。所以语句p.print()没有编译(你应该在你的问题中说过,并加入了确切的错误信息)。

要打印数组的所有页面,您需要遍历数组:

for (Page page : p) {
    page.print();
}

请避免使用单字母变量,并对数组和集合使用复数形式:Page[] pages = new Page[2];