【发布时间】:2019-09-04 18:21:13
【问题描述】:
即使我正确地实例化了我的对象,我也发现很难使用我的方法。关于我哪里出错的任何想法?
示例:我尝试编译 java 文件,但我得到的错误是
“不兼容的类型:字符串无法转换为书籍”
我认为问题是我的实例化对象被强制转换为字符串,但问题是我使用了正确的语法来调用字符串。但是,它仍然不会将其读取为字符串,并表示无法将实例化的对象转换为“Books”类。
我已经搜索过它,但他们只说该对象尚未创建。但是,我检查了我的代码,甚至在将它放入方法参数之前就已经实例化了我的对象。
我什至尝试自己打印具有特定特征的对象,结果很好。所以我猜它会一直上升,直到它被放入一个方法中。
我不明白的一件事是我需要将该对象引用到方法中。
这是我的代码:
class Books{
String type;
int pages;
Books[] booklist;
int bookcounter = 0;
//Constructor to initialize the object "book"
Books(int input){
if(input == 1){
this.type = "Math";
this.pages = 5;
}
if(input == 2){
this.type = "Physics";
this.pages = 9;
}
if(input == 3){
this.type = "Economics";
this.pages = 20;
}
}
//This method needs to add the instantiated object to the array list
void addbooktype(Books kind){
System.out.println("You chose: " + kind);
System.out.println("Adding to the list...");
booklist[bookcounter++] = kind;
}
void printbooks(){
for(int i = 0; i <= bookcounter; i++){
int y = i+1;
System.out.println("Book #"+ y + "is: " +this.booklist[i].type);
System.out.println("With pages of: " + this.booklist[i].pages);
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int bookchoice;
int choice;
String booktype;
int booknum = 0;
do{
System.out.println("===========Menu===========");
System.out.println("[1] - Pick a book \n[2] - Print book list\n[0] - Exit");
System.out.println("==========================");
System.out.print("Choice: ");
choice = sc.nextInt();
switch(choice){
//Selects and adds a book to the list
case 1:
System.out.println("Choose your book: ");
bookchoice = sc.nextInt();
Books book = new Books(bookchoice);
System.out.println(book.type);
booktype = book.type;
book.addbooktype(booktype);
booknum++;
break;
//Prints the book list
case 2:
System.out.println("List of Books: ");
book.printbooks();
break;
case 0:
System.out.println("Exit");
return;
default: System.out.println("Input not found.");
}
}while(choice!=0);
}
}
我得到的错误是关于“book.addbooktype(booktype);”
这就是让我烦恼的地方,我打印了反对意见,甚至将其放入 String 容器中,但它仍然拒绝它。我不知道我哪里错了。当它进入方法时,它不会读取参数。有什么想法吗?
【问题讨论】:
-
一个类应该代表一些东西。你的
Book类是代表一本书还是一本书的列表? -
我想要的是它代表一个书籍列表,这就是我包含“Books [] booklist”数组的原因。还是错了?
-
Book.Type只是字符串。您需要传递对象本身,即book或更改方法以接受String。 -
那么它不应该有
type和pages字段,因为书籍列表没有“类型”,也没有“页面”。我认为您需要将此类重命名为BookList并将type和pages移动到一个新类Book中。 -
欢迎来到 StackOverflow。正如tour 中所述,此站点是有用问题及其答案的存储库,不是教程站点或帮助/讨论论坛。我担心您对一些基本概念(例如类、类型和实例)有一些根本性的误解,不幸的是,SO 并没有真正设置为教程“论坛”。请拨打tour,访问help center,尤其是阅读How to Ask和Why is “Can someone help me?” not an actual question?,了解如何有效使用本网站。
标签: java arrays class constructor instantiation