我創建了 3 個類:Books、autors 和 main 類。我在其中創建了 start() 方法和物件(任務需要)。在這里我的鱈魚請有人解釋一下還是有更好的方法來做到這一點?我創建陣列串列,有更好的方法嗎?我非常感謝任何幫助
import java.util.ArrayList;
import java.util.Scanner;
public class BookAuthorStorage<E> {
ArrayList<Book> bookStorage = new ArrayList <>();
ArrayList<Author> authorsStorage = new ArrayList<>();
public void start() {
Book Alchemist = new Book("Alchemist", "That everything is possible", 100, "Paulo Coelho");
Book HarryPotter = new Book("Harry Potter", "The Kind take over evil", 300, "J.K. Rowling");
Book It = new Book("It", "Scary book", 200, "Stephen King");
Author StephenKing = new Author("Stephen", "King", 46, "male", "[email protected]", "It");
Author Rowling = new Author("Joan", "Rowling", 39, "female", "Rowling.com", "Harry Potter");
Author Coelho = new Author("Paulo", "Coelho", 60, "male", "Coelho.com", "Alchemist");
Scanner scan = new Scanner(System.in);
System.out.println(" Enter 1 to show all books or 2 for authors and 3 for exit");
while (true) {
int choice = scan.nextInt();
switch (choice) {
case 1 -> bookStorage.forEach(System.out::println);
case 2 -> authorsStorage.forEach(System.out::println);
case 3 -> {
System.out.println(" Exiting");
return;
}
default -> System.out.println("Enter again");
}
}
}
public static void main(String[] args) {
BookAuthorStorage bookAuthorStorage1 = new BookAuthorStorage();
bookAuthorStorage1.start();
}
}
當我嘗試列印時,它會列印 null、null、null。我在 Book 和 Author 類中覆寫了 String
public class Author {
public String name;
public String surname;
public int age;
public String gender;
public String email;
Author(String name, String surname, int age, String gender,String email, String book){
}
public String toString(){
return this.name this.surname this.age this.email this.gender ;
}
}
public class Book {
public String title;
public String description;
public int count = 1000;
public String author;
Book(String title, String description, int count, String author){
}
@Override
public String toString(){
return this.author this.description this.title this.count;
}
}
uj5u.com熱心網友回復:
Book為&使用所有成員變數創建引數化建構式,Author然后初始化兩個類,BookAuthorStorage如下所示:
Author(String name, String surname, int age, String gender,String email, String book){
this.name=name;
this.surname=surname;
this.age=age;
this.gender=gender;
this.email=email;
this.book=book;
}
內部BookAuthorStorage呼叫:
Book Alchemist = new Book("A","B",1,"C");
..
Author StephenKing = new Author("D","E",1,"F","G");
..
String目前在原始代碼中,除了成員變數之外,您沒有初始化任何成員int變數。所以這就是你的輸出總是有價值的原因null。int
uj5u.com熱心網友回復:
在建構式中,引數和內部變數之間沒有隱式關系。
盡管名稱相同,但您必須指出要對引數執行的操作:
Book(String title, String description, int count, String author){
this.title = title;
this.description = description;
this.count = count;
this.author = author;
}
最好區分兩者以避免錯誤,因為引數的名稱可以在建構式中使用。
Book(String aTitle, String aDescription, int aCount, String anAuthor){
this.title = aTitle;
this.description = aDescription;
this.count = aCount;
this.author = anAuthor;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471061.html
上一篇:附加兩個串列串列的串列
