[英]How can I use user input in a String array to call a different object's method?
So, I am writing a simple game in Java and there are multiple skills that a user can use. 因此,我正在用Java编写一个简单的游戏,并且用户可以使用多种技能。 Below is an example of a skill instantiated and named "a". 以下是实例化并命名为“ a”的技能的示例。 In my main method, I instantiated many skills all with names of lowercase letters to make it easy. 在我的主要方法中,我实例化了许多技巧,所有技巧都使用小写字母,以使其变得容易。 Then I asked the user which skills they would like to use and they would choose them by typing in lower case letters that corresponded with the skill. 然后,我问用户他们想使用哪些技能,他们将通过键入与该技能相对应的小写字母来选择它们。
String[] playerSkill = new String[3];
Skill a = new Skill("One", "Two", 3);
System.out.println("Type in a lowercase letter corresponding to each skill.");
System.out.println("a. " + a.getName() + " - " + a.toString());
The user types in "a". 用户键入“ a”。
playerSkill[0] = scan.next();
System.out.println(playerSkill[0].getName());
The problem is that the playerSkill[0] is a String and cannot be used to call an object method. 问题是playerSkill [0]是一个字符串,不能用于调用对象方法。 I get the compiler error "Cannot find symbol- method getName()". 我收到编译器错误“找不到符号方法getName()”。
Below is the code for my Skill class: 下面是我的Skill类的代码:
public class Skill {
private String name;
private String description;
private int power;
public Skill(String n, String d, int p) {
name = n;
description = d;
power = p;
}
public String getName() {
return name;
}
public String toString() {
return description;
}
Since each String has the exact same name as the Skill objects, I thought calling the getName() method would work but the types seem to be incompatible. 由于每个String都具有与Skill对象完全相同的名称,因此我认为调用getName()方法会起作用,但类型似乎不兼容。 What would be the best way to work around this problem? 解决此问题的最佳方法是什么?
You could use a key/value to associate a Skill object with a String "id", something like this: 您可以使用键/值将Skill对象与字符串“ id”相关联,如下所示:
HashMap<String, Skill> hash = new HashMap<String, Skill>();
Skill a = new Skill("One", "Two", 3);
hash.put(playerSkill[0], a); // Add all your skill objects to this map
System.out.println(hash.get(playerSkill[0]).getName());
Okay, so you have a random string the user typed in ("a"). 好的,因此您有一个用户输入的随机字符串(“ a”)。 And you have a variable you call "a". 您有一个变量称为“ a”。 There is no relationship between these. 这些之间没有关系。
The easiest solution is a series of if-statements. 最简单的解决方案是一系列if语句。
if (playerSkill[0].equals("a")) {
System.out.println(a.getName());
}
else if playerSkill[0].equals("b")) {
System.out.println(a.getName());
}
This is gross, but it works. 这很麻烦,但是行得通。 A better way would be to stuff all your Skill objects into an array and iterate over the array to find the one that corresponds to the one you want. 更好的方法是将所有Skill对象填充到一个数组中,然后遍历该数组以找到与所需对象相对应的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.