0

我是一名学生,正在从事一个项目,使用数组创建类来模拟组合。我假设到目前为止我一切都正确,但似乎我在驱动程序类中的打印语句有问题。我不确定这是否与我将两者链接在一起的方法有关。任何信息将不胜感激。

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(); 
   }
}
4

1 回答 1

1

p是类型Page[],即“页面数组”。而且数组没有print()方法。因此该语句p.print()无法编译(您应该在问题中这么说,并加入了确切的错误消息)。

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

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

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

于 2012-05-11T21:27:31.447 回答