为什么将类a设置为类b有效?/如何使我的方法通用?

huangapple go评论80阅读模式
英文:

Why does setting class a to class b work?/How can I make my method universal?

问题

以下是你要翻译的内容:

在我开始之前,我想先声明一下。我实际上不太理解这里发生了什么,所以如果我的段落没有太多意义,我深感抱歉。我会尽力表达我的问题,希望你们能帮助我。所以,开始了。

我一直在开发一个基本的基于测试的冒险游戏/地牢探险游戏。在为找到怪物时创建遭遇方法时,我意识到我需要一种遍历充满怪物类的Hashtable的方法。问题是,我将键设置为字符串,以便在想要将特定物品添加到玩家存储中或将特定怪物添加到战斗中时更容易访问。因此,我决定创建一个方法,该方法将接收我提供的Hashtable,然后返回一个随机键,然后我将使用该键从我的数据库中获取怪物。我尝试创建一个适用于所有具有字符串、类格式的Hashtable的方法,以下是我尝试的解析代码示例。

for (String key : table.keySet()) {
    if (num_of_loops_to_do == times_looped) {
        return key;
    }
}

这不起作用,因为程序抱怨表格(我是这样传递的:Hashtable table)是一个对象,因此如果强制尝试从中提取键,程序将会出错。现在如果有人能解释一下这个问题,我会很感激,但这不是我问题的核心。最终,我改变了我的尝试方法,使用了一个try-catch系统,我会有两个与程序中的两个数据库Hashtable具有相同类型的Hashtable。然后,程序将尝试将提供的Hashtable设置为其中一个,如果失败了就将其放入另一个。有趣的是,我将我的怪物类传递给了方法,它将其设置为一个将数据存储为字符串、物品的Hashtable。现在,由于我只从中获取键,所以类发生了变化似乎并不重要,但怪物如何在不引发任何错误的情况下变成了物品?我的意思是,我猜两者都按以下顺序接收数据(int、int、String、int),所以创建可能可以工作,我想这就是发生的情况。我在这方面是正确的吗?这是个问题吗?由于我只使用键,我是否可以以某种方式使这个方法通用,只从表格中获取键,而不是键和值?

这是我的物品类。

static class item {
    private int durability;
    private int damage;
    private String name;
    private int rarity_level;
    item(int durability, int damage, String name, int rarity_level) {
        this.durability = durability;
        this.damage = damage;
        this.name = name;
        this.rarity_level = rarity_level;
    }
    String get_name() {
        return name;
    }
    // 其他方法...
}

这是我的怪物类。

static class monster {
    private int health;
    private int damage;
    private String name;
    private int level;
    monster(int health, int damage, String name, int level) {
        this.health = health;
        this.damage = damage;
        this.name = name;
        this.level = level;
    }
    String get_name() {
        return name;
    }
    // 其他方法...
}

最后,这是我的方法。

public static String get_Ran_Object_From_Dict(Hashtable table) {
    Random rand = new Random();
    int object_num_to_retrieve = rand.nextInt(table.size());
    Hashtable<String, Data.item> item_data_base = new Hashtable<String, Data.item>();
    Hashtable<String, Data.monster> monster_data_base = new Hashtable<String, Data.monster>();
    try {
        item_data_base = table;
    } catch (Exception e) {
        monster_data_base = table;
    }
    int num_looped = 0;
    System.out.println(item_data_base.size());
    System.out.println(monster_data_base.size());
    if (monster_data_base.size() > 0) {
        System.out.println("monster");
        for (String key : monster_data_base.keySet()) {
            if (num_looped == object_num_to_retrieve) {
                return key;
            }
            num_looped += 1;
        }
    } else {
        System.out.println("item");
        for (String key : item_data_base.keySet()) {
            if (num_looped == object_num_to_retrieve) {
                return key;
            }
            num_looped += 1;
        }
    }
    return "System_fail";
}
英文:

So before I start this off I would like to give a little disclaimer. I do not really understand what is happening here so I apologize if my paragraph does not make much sense. I will try my best to convey my question, and, hopefully, y'all will be able to help me. So here goes.

I have been working on a basic test based adventure game/dungeon crawler. While creating an encounter method for when you find a monster, I realized that I needed a way to parse through my Hashtables full of my monster classes. Problem was, I had set the keys to Strings for easier access when wanting to add a specific item to the player's storage or to add a specific monster to a fight. So I decided to create a method which would receive a Hashtable I fed it and spit back out a random key, which I would then use to get the monster from my database. I attempted to create a method that would work for all Hashtables with a String, class format, and a sample of my attempted parsing code resides below.

for(String key: table.getkeys())
{
    if(num_of_loops_to_do==times_looped)
    {
        return key;
    }
}

This didn't work, as the program complained about the table (which I fed like so(Hashtable table)) was an object and therefore the program would have a seizure if it was forced to try to pull keys out of it. Now if someone can explain this, I would appreciate it, but it is not the core of my question. Eventually, I changed my path of attack to a try-catch system where I would have two Hasthables that shared the same types as the two database Hashtables in my program. Then the program would try to set the provided hashtable to one and if that failed stick it in another. The funny thing is, I fed my method my monster class, and it set it to a Hashtable that stores data as String, item. Now, since I only am getting the key from these I guess it doesn't really matter what happens to the class, but how is monster changed to item without any errors being thrown? I mean I guess they both take data in the following order (int, int, String, int) so I guess the creation could work, and I assume this is what happened. Am I correct in this? Is this a problem? Since I'm using just the key can I somehow make the method universal where it only takes the keys from table instead of the keys and values?

Here is my item class.

static class item
	{
		private int durability;
		private int damage;
		private String name;
		private int rarity_level;
		item(int durability, int damage, String name, int rarity_level)
		{
			this.durability=durability;
			this.damage=damage;
			this.name=name;
			this.rarity_level=rarity_level;
		}
		String get_name() 
		{
			return name;
		}
		int get_durability() 
		{
			return durability;
		}
		int get_damage() 
		{
			return damage;
		}
		void change_durability(int change_in_durabilty) 
		{
			durability=durability+change_in_durabilty;
		}
		int get_rarity_level() 
		{
			return rarity_level;
		}
	}

Here is my monster class.

static class monster
	{
		private int health;
		private int damage;
		private String name;
		private int level;
		monster(int health, int damage, String name, int level)
		{
			this.health=health;
			this.damage=damage;
			this.name=name;
			this.level=level;
		}
		String get_name() 
		{
			return name;
		}
		int get_health() 
		{
			return health;
		}
		int get_damage() 
		{
			return damage;
		}
		void change_health(int change_in_durabilty) 
		{
			health=health+change_in_durabilty;
		}
		int get_level() 
		{
			return level;
		}
	}

And finally, here is my Method.

public static String get_Ran_Object_From_Dict(Hashtable table) 
	{
		Random rand=new Random();
		int object_num_to_retrieve=rand.nextInt(table.size());
		Hashtable&lt;String, Data.item&gt; item_data_base=new Hashtable&lt;String, Data.item&gt;();
		Hashtable&lt;String, Data.monster&gt; monster_data_base=new Hashtable&lt;String, Data.monster&gt;();
		try {
			item_data_base=table;
		}
		catch(Exception e)
		{
			monster_data_base=table;
		}
		int num_looped=0;
		System.out.println(item_data_base.size());
		System.out.println(monster_data_base.size());
		if(monster_data_base.size()&gt;0) {
			System.out.println(&quot;monster&quot;);
			for(String key : monster_data_base.keySet()) 
			{
				if(num_looped==object_num_to_retrieve) 
				{
					return key;
				}
				num_looped+=1;
			}
		}
		else 
		{
			System.out.println(&quot;item&quot;);
			for(String key : item_data_base.keySet()) 
			{
				if(num_looped==object_num_to_retrieve) 
				{
					return key;
				}
				num_looped+=1;
			}
		}
		return &quot;System_fail&quot;;
	}

答案1

得分: 0

我相信它起作用的原因是,当item_data_base被设置为table时,item_data_base的原始参数被覆盖。所以最后一个问题,为什么仅仅使用原始的table值时,它不起作用呢?

(正常工作的代码)

public static String get_Ran_Object_From_Dict(Hashtable table) 
{
    // 通过创建具有定义参数的字典,然后将其设置为table,它就不会出错。
    Random rand = new Random();
    int object_num_to_retrieve = rand.nextInt(table.size());
    Hashtable<String, String> hashtable = new Hashtable<String, String>();
    hashtable = table;
    int num_looped = 0;
    for (String key : hashtable.keySet()) 
    {
        if (num_looped == object_num_to_retrieve) 
        {
            return key;
        }
        num_looped += 1;
    }
    return "System_fail";
}

(有问题的代码)

public static String get_Ran_Object_From_Dict(Hashtable table) 
{
    Random rand = new Random();
    int object_num_to_retrieve = rand.nextInt(table.size());
    int num_looped = 0;
    for (String key : table.keySet()) 
    {
        if (num_looped == object_num_to_retrieve) 
        {
            return key;
        }
        num_looped += 1;
    }
    return "System_fail";
}
英文:

I believe the reason it works is that when item_data_base is set equal to table the original parameters of item_data_base are overwritten. So one last question, why does that work when just using the raw table value doesn't?

(Working code)

public static String get_Ran_Object_From_Dict(Hashtable table) 
	{
		//By creating dictionary with defined parameters I can then set it to table and it wont explode.
		Random rand=new Random();
		int object_num_to_retrieve=rand.nextInt(table.size());
		Hashtable&lt;String, String&gt; hashtable=new Hashtable&lt;String, String&gt;();
		hashtable=table;
		int num_looped=0;
		for(String key :hashtable.keySet()) 
		{
			if(num_looped==object_num_to_retrieve) 
			{
				return key;
			}
			num_looped+=1;
		}
		return &quot;System_fail&quot;;
	}

(Broken Code)

public static String get_Ran_Object_From_Dict(Hashtable table) 
	{
		Random rand=new Random();
		int object_num_to_retrieve=rand.nextInt(table.size());
		int num_looped=0;
		for(String key :table.keySet()) 
		{
			if(num_looped==object_num_to_retrieve) 
			{
				return key;
			}
			num_looped+=1;
		}
		return &quot;System_fail&quot;;
	}

huangapple
  • 本文由 发表于 2020年9月14日 23:51:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63887740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定