2015-01-02 5 views
-1

수업에 대한 초보자 안내서는 아래 작업을 수행해야합니다.필드의 클래스 유형 변경

1) Create a class called User. 
    a) Add fields for name, age, and location. 
    b) Add a method called toString. 
2) In the book class: 
    a) Change the author field to be of type User. 
    b) Modify the toString method to include the author's name. 

다음은 I 형 사용자의로 저자 필드를 변경하는 방법을 잘 모르겠어요 내 코드

public class User { 
    public String name; 
    public int age; 
    public String location; 
    public String author; 

    public String toString() { 
     String description1 = "Name:" + name + " Age:"+ age + " Location:" + location + " Reading:" + author; 
     return description1; 
    } 

} 

public class Book { 

    public String title; 
    public String author; 
    public int numPages; 
    public int isbn; 

    public Book(String title, String author, int numPages, int isbn){ 
     this.title = title; 
     this.author = author; 
     this.numPages = numPages; 
     this.isbn = isbn; 
    } 

    public String toString() { 
     String description = "Title:" + title + "Author"+ author + "Num. of pages" + numPages + "ISBN" + isbn; 
     return description; 
    }  
} 

입니다. 다른 자습서를 보면 나에게 아주 기본적인 것처럼 보이는 것에 대한 답을 찾지 못하는 것 같습니다./

어떤 조언이 있습니까?

+0

:

public String toString() { String description = "Title:" + title + "Author"+ author.getName() + "Num. of pages" + numPages + "ISBN" + isbn; return description; } 

와 생성자도로 변경해야 'author' 필드를 선언하는 곳에서. 선언의 어느 부분이 필드의 유형입니까? 그것을 찾아서'User' ...로 변경하고, 그 밖의 무엇을 (예 : 들어오는 값이'String' 일 때 생성자로부터 값을 할당하는 것과 같이) 보게됩니다. 여기에 어떤 문제가 있는지는 명확하지 않습니다. 어떤 작업이 당신에게 개념상의 문제를 야기시키고 있습니다. –

+0

@JonSkeet 제대로하고 있는지 잘 모르겠습니까? 저자가 두 가지 유형 모두에 있다고 선언하고있는 것 같지만 책 클래스를 수정해야한다고 생각하기 때문에 책 클래스에서만 변경해야한다고 생각합니다. 나는 그저 책 클래스에서'저자 '를 제거합니까? –

+0

아니요, 제거하지 마십시오. 지침이 말하는 것처럼 유형을 변경합니다. 'Book' 클래스에서'author' 필드를 찾고, 그 타입을'User'로 변경하십시오. * 별개의 문제로서, 왜'User' 클래스에'author' 필드가 있는지 분명하지 않습니다. (제거해야합니다 - 사용자는 작성자가 없습니다 ...) –

답변

0

대신

public String author; 

의 당신은

그래서
public User author; 

생성자의

public Book(String title, User author, int numPages, int isbn){ 
    this.title = title; 
    this.author = author; 
    this.numPages = numPages; 
    this.isbn = isbn; 
} 

변경 그리고 대신

public String toString() { 
    String description = "Title:" + title + "Author"+ author + "Num. of pages" + numPages + "ISBN" + isbn; 
    return description; 
} 
을 사용

당신은 private User author;에 클래스 Book 변화 public String author;

public String toString() { 
    String description = "Title:" + title + "Author"+ author.name + "Num. of pages" + numPages + "ISBN" + isbn; 
    return description; 
} 
+0

changin 생성자 인수도 필요합니다. –

+0

예, 게시 한 것처럼 나타났습니다. 감사. – Matt

0

을 사용하고 또한 toString() 새로운 모습 것 : 잘 보면

public Book(String title, User author, int numPages, int isbn){