There's this task I'm working on, in which I have to make an arraylist based on an Author class, which has as its properties: ID, author's name, book and nationality. This aside, I had to make another class, which receives as a parameter the ID, and returns the corresponding author's info. My problem is that I wrote the code, but no matter what ID my input receives, it always retrieves the same author's information. Could anyone help me on this?
Author.java
public class Author {
private int id;
private String name;
private string book;
private string country;
public Author(int id, String name, String book, String country) {
this.id = id;
this.name = name;
this.book = book;
this.country = country;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getBook() {
return book;
}
public int getCountry() {
return country;
}
@Override
public String toString() {
return "Id: " + this.id + ", Name: " + this.name + ", Book:" + this.book + ", Country:" + this.country;
}
}
GetAuthor.java (class used to retrieve Author's info based on the ID)
public class GetAuthor {
public Author returnAuthor(int id, ArrayList<Author> list) {
Author author = null;
id = 0;
for (int i = 0 ; i < list.size() ; i++) {
if(author == null || author(i).getId() == id) {
author = list.get(i);
id = list.get(i).getId();
}
}
return author;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Author w1 = new Author(1, "Franz Kafka", " The Metamorphosis", "Austria");
Author w2 = new Author(2, "Neil Gaiman", "Sandman", "England");
Author w3 = new Author(3, "Jack Kerouac", "On The Road", "USA");
ArrayList<Author> authors = new ArrayList<>();
authors.add(w1);
authors.add(w2);
authors.add(w3);
for(int i = 0 ; i < authors.size() ; i++){
System.out.println(authors.get(i));
}
Scanner scan = new Scanner(System.in);
System.out.print("Enter the author's ID: ");
int num = scan.nextInt();
GetAuthor theAuthor = new GetAuthor();
Author author = theAuthor.returnAuthor(num,authors);
System.out.println(author);
}
}