import java.util.Scanner;
public class Library {
public static void main(String [] args) {
/*
* Patron class: name + 3 books
* Book class: author + title
*/
Book TwelveYears = new Book ("12 Years a Slave", "Solomon Northup");
Book Diary = new Book ("The Diary of John Smith", "John Smith");
Book Fahrenheit451 = new Book ("Fahrenheit 451", "Ray Bradbury");
Book Gatsby = new Book ("The Great Gatsby", "Fitzgerald");
Book Antigone = new Book ("12 Years a Slave", "Sophocles");
System.out.println("Welcome to library account management! Here is a list of books to check out: " +TwelveYears.getBookTitle()+", "+Diary.getBookTitle()+", "+Fahrenheit451.getBookTitle()+", "+Gatsby.getBookTitle()+", "+Antigone.getBookTitle()+".");
Scanner sc=new Scanner(System.in);
System.out.println("Enter your name!");
String enteredName = sc.nextLine();
System.out.println("Enter your first book! Enter it exactly as seen above.");
String book1 = sc.nextLine();
System.out.println("Enter your second book!");
String book2 = sc.nextLine();
System.out.println("Enter your third book!");
String book3 = sc.nextLine();
Patron patron1 = new Patron(enteredName, book1, book2, book3);
book1 = //line I need help on
System.out.println("Here are the books you are checking out: " +book1+ ", " +book2+ ", " +book3+ ".");
}
}
在这里,我正在尝试使用book1变量,并将其与正确的类成员进行协调。我认为解释我在这里尝试做什么的最好方法是举个例子:如果用户输入的book1是“12年奴隶”,那么book1的值将是“TwelveYears”,其中一个类定义在开头附近代码,所以在将来,我可以使用像book1.getAuthor这样的访问器/ mutator方法。
我只是在学习java,所以我没有办法正确解释这个问题,所以我道歉,但是我会非常感激任何帮助,如果我想要的话,我很乐意回答任何问题。在这里,但我希望我很清楚。
谢谢!
答案 0 :(得分:2)
如果必须根据字符串决定要创建哪个对象,则只需对书名进行一系列检查,并确定要创建的对象。假设TwelveYears
和GreatGatsby
都从Book
继承,那么您可以这样做:
Book unknownBook;
switch(bookTitleScanned)
{
case("Twelve Years a Slave")
unknownBook = new TwelveYears();
case("Great Gatsby")
unknownBook = new GreatGatsby();
...
}
由于polymorphism,您的Book
引用可以指向TwelveYears
和GreatGatsby
。
但是这可能是做你想做的更好的方法:
假设所有用于您目的的对象都非常相似(在您的示例中,book
如TwelveYears
和GreatGatsby
),如果您只编写一个类可能会更容易,比如Book
,让该类进行所有处理,而不是创建单独的类。
然后,您只需创建Book
类的实例,将书名称作为属性分配给这些实例,并将其收集到某种Collections对象中,这将使您的代码更加灵活和可重用(嘿,如果你把它们放在Book
中,你可以循环遍历ArrayList
。
具体而言,您的Book
类可以有一个属性bookName
,以及
public void getBookName()
{
return bookName;
}
甚至:
public void handleParticularBook()
{
if (bookName.equals("GreatGatsby"))
System.out.println("My favorite book!");
else if ...
}
答案 1 :(得分:1)
将所有图书放在Function GrafMet(Rng As Range) As String
Dim celda As Range
Dim currentcell As Range
Dim nextcell As Range
Set currentcell = ActiveCell
For Each celda In Rng
valor1 = celda.Value
Set nextcell = currentcell.Offset(0, valor1)
nextcell.Interior.ColorIndex = 3
Set currentcell = nextcell.Offset(0, valor1 * -1)
Next celda
' this is just for returning something
Dim ppp As String
ppp = "OK"
GrafMet = ppp
End Function
中。如果与ArrayList<Book>
ArrayList
并使用book1.equals(a1.get(i).getBookName)