所以我对Java很陌生...已经有4个星期了......温柔。
我试图让我的takeItem方法(下面)将itemName变量传递回我的Player类,这样我就可以将当前房间的项目添加到我的播放器中。我得到编译器错误:类Item中的构造函数项不能应用于给定的类型..
我的最终目标是让玩家类在将其从房间中移除后抓住该物体。
takeItem方法:
private void takeItem(Command command)
{
if(!command.hasSecondWord()) {
// if there is no second word, we don't know where to go...
System.out.println("Take what?");
System.out.println();
return;
}
String itemName = command.getSecondWord();
Item theItem;
// Try to take an item.
theItem = new Item(player.getCurrentRoom().removeItem(itemName));
if (theItem == null)
{
System.out.println("There is no item!");
}
else
{
player.addItem(theItem);
player.getItemsCarried();//print item info
}
玩家等级:
//above code omitted//
public void setCurrentRoom(Room room)
{
currentRoom = room;
}
public Room getCurrentRoom()
{
return currentRoom;
}
//code below omitted//
public void addItem (Item thingy)
{
items.put(thingy.getName(), thingy);
}
//code below omitted//
项目类别:
public class Item
{
// instance variables - replace the example below with your own
private String name;
private String description;
private int weight;
/**
* Constructor for objects of class Item
*/
public Item(String n, String d, int w)
{
name = n;
description = d;
weight = w;
}
//code below omitted//
房间等级:
public class Room
{
private String description;
private HashMap <String, Room> exits;
private HashMap <String, Item> items;
//some code below omitted//
public Room (String description)
{
this.description = description;
exits = new HashMap<>();
items = new HashMap<>();
}
public void addItem (Item thingy)
{
items.put(thingy.getName(), thingy);
}
public String removeItem(String thingy)
{
items.remove(thingy);
return thingy;
}
//code below omitted
答案 0 :(得分:0)
Item
类中的构造函数需要两个String
个参数和一个int
,但是您尝试通过只传入一个{{1}来创建新的Item
(String
方法返回的任何内容)。您可以更改removeItem()
方法,以便返回已移除的removeItem()
,在这种情况下您应该更改
Item
到
theItem = new Item(player.getCurrentRoom().removeItem(itemName));
或者您可以使用必要的参数创建新的theItem = player.getCurrentRoom().removeItem(itemName);
。