将项目添加到房间,未定义类型错误

编辑:如果我不清楚(对不起,我是Java的初学者),我只是想添加将项目添加到房间的可能性,但是,我希望项目方面位于其自己的类中,就像目前一样。尽管在目前的状态下,它不起作用。


我试图让物品出现在我的游戏的房间中,所以我制作了一个单独的物品类,其中相关代码是


public class Items 

{


private String itemDescription;

private int itemWeight;

/**

 * Add an item to the Room

 * @param description The description of the item

 * @param weight The item's weight

 */

public void addItem(String description, int weight) 

{

    itemDescription = description;

    itemWeight = weight;               

}


/**

 * Does the room contain an item

 * @param description the item

 * @ return the item's weight or 0 if none

 */

public int containsItem(String description) 

{

    if (itemDescription.equals(description)) 

    {

        return itemWeight;

    }

    else

    {

        return 0;

    }

}


/**

 * Remove an item from the Room

 */

public String removeItem(String description) 

{

    if (itemDescription.equals(description)) 

    {

        String tmp = itemDescription;

        itemDescription = null;

        return tmp;

    }

    else 

    {

        System.out.println("This room does not contain" + description);

        return null;

    }

}




public String getItemDescription() 

{

    return this.itemDescription;

}


public void setItemDescription(String itemDescription) 

{

    this.itemDescription = itemDescription;

}


public int getItemWeight() 

{

    return this.itemWeight;

}


public void setItemWeight(int itemWeight) 

{

    this.itemWeight = itemWeight;

}


public String getCharacter() 

{

    return this.character;

}


public void setCharacter(String character) 

{

    this.character = character;

}

}

在我单独的游戏类中,我尝试将其链接到我的游戏类中,就像这样


     // initialise room exits

        outside.setExit("north", lab);

        outside.addItem("notebook", 2); 

就像我对游戏出口所做的那样。但是,我收到一条错误消息


The method addItem(String, int) is undefined for the type 

Room

我认为这是因为,名为“Room”的类没有任何对“item”的引用,但是我不确定如何实现这一目标?任何指导将不胜感激。



慕妹3146593
浏览 46回答 2
2回答

30秒到达战场

The method addItem(String, int) is undefined for the type Room因为您的房间类中没有 addItem(String, Item) 方法定义。在尝试调用之前,将此函数添加到 Room 类中。或者如下图修复如果没有它,您将收到编译错误。看到你的评论,让我给你一些建议,但要小心,因为我不知道你的确切需求。import java.util.HashMap;import java.util.Set;import java.util.ArrayList;public class Room {        public Items item = new Items();       ...........在调用类时使用它就像         outside.item.addIem(...)

叮当猫咪

您可以在此处将项目逻辑与房间逻辑混合。你的addItem函数应该是 Item 的构造函数您应该在 Room 类中具有 addItem 函数,该函数实例化一个新项目(如果您想在房间中放置超过 1 个项目,则可能将其存储在列表/哈希中)该containsItem方法也应该位于 Room 类中
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java