gpt4 book ai didi

java - 将 String 转换为另一个类中的数组名称

转载 作者:行者123 更新时间:2023-12-02 04:35:09 26 4
gpt4 key购买 nike

我是一名业余程序员,我想知道是否可以通过特定方式解决问题。

public class Stats {

public static int[] Hero = {20, 20, 10, 10, 10};
public static int[] Villain = {20, 20, 10, 10, 10};

public static void name(int[] name) {
//If you insert an array it will print all its values
System.out.println("Health: " + name[1] + "/" + name[0]);
System.out.println("Damage: " + name[2]);
System.out.println("Defense: " + name[3]);
System.out.println("Agility: " + name[4]);
return;
}

这就是我想要使用的,如果我使用“英雄”或“恶棍”来调用它,它就可以正常工作。

    public class UserInterface extends JPanel implements MouseListener, MouseMotionListener {

//A lot of code in between that is not of notice right now

@Override
public void mouseClicked(MouseEvent e) {
if (" ".equals(CHESS.Board[e.getY() / squareSize][e.getX() / squareSize]) == false) {
//Checks if I pressed on a legit space on the map

String name = (CHESS.Board[e.getY() / squareSize][e.getX() / squareSize]);
//In this scenario 'name' will be a String called "Hero"

System.out.println("Name: " + name);
//Will write out 'Name: Hero'

Stats.name(Stats.Hero);
//Works fine

Stats.name(Stats.name);
//Does not work

}
}

现在我想要的是根据我单击的内容调用正确的数组。目前我只有名为“英雄”和“恶棍”的阵列,但最终 map 上肯定会有超过 50 个阵列可供选择。显然只是写 stats.name(Stats.name);不起作用,因为 name 是一个 String 并且它需要一个 int[]。

但是有没有一种方法可以使用我的字符串“名称”,以便我可以调用在不同类中命名相同内容的 int[] 数组?

最佳答案

我认为您想要做的是按名称查找对象。您无法按照字面上的方式执行此操作,但它很常见,而且您不必添加太多代码。

假设您有一款 RPG 游戏,并且有团队成员,每个小电脑人都通过名字来识别团队成员。

Map<String,RpgPerson> team = new HashMap<>();

这里我们有一种方法将字符串(名称)映射到我们想要的对象(具有所有统计信息的对象)。我使用上面的建议来创建一个“Person”对象,因为它确实比使用数组更好。

这是一个简单的示例:

public class RpgPersonExample
{
public static void main( String[] args )
{
Map<String, RpgPerson> team = new HashMap<>();
team.put( "Sgt. Mayhem", new RpgPerson( 100, 10, 0 ) );
team.put( "Wizard", new RpgPerson( 100, 1, 10 ) );
team.put( "Dragon", new RpgPerson( 1000, 100, 100 ) );

System.out.println( team.get( "Dragon" ) );
System.out.println( team.get( "Wizard" ) );
}

}

class RpgPerson
{

private int hits;
private int strength;
private int magic;

public RpgPerson( int hits, int strength, int magic )
{
this.hits = hits;
this.strength = strength;
this.magic = magic;
}

@Override
public String toString()
{
return "RpgPerson{" + "hits=" + hits + ", strength=" +
strength + ", magic=" + magic + '}';
}

}

关于java - 将 String 转换为另一个类中的数组名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30926154/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com