为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3146593 2024-01-05 10:21:18
编辑:如果我不清楚(对不起,我是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”的引用,但是我不确定如何实现这一目标?任何指导将不胜感激。
查看完整描述

2 回答

?
30秒到达战场

TA贡献1828条经验 获得超6个赞

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(...)


查看完整回答
反对 回复 2024-01-05
?
叮当猫咪

TA贡献1776条经验 获得超12个赞

您可以在此处将项目逻辑与房间逻辑混合。

  1. 你的addItem函数应该是 Item 的构造函数

  2. 您应该在 Room 类中具有 addItem 函数,该函数实例化一个新项目(如果您想在房间中放置超过 1 个项目,则可能将其存储在列表/哈希中)

  3. containsItem方法也应该位于 Room 类中


查看完整回答
反对 回复 2024-01-05
  • 2 回答
  • 0 关注
  • 39 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信