0

So, I am writing a simple game in Java and there are multiple skills that a user can use. Below is an example of a skill instantiated and named "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".

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. I get the compiler error "Cannot find symbol- method getName()".

Below is the code for my Skill class:

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. What would be the best way to work around this problem?

1
  • Create a Player class that has Skills as an attribute. Commented Feb 20, 2015 at 15:25

2 Answers 2

1

You could use a key/value to associate a Skill object with a String "id", something like this:

    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());
Sign up to request clarification or add additional context in comments.

Comments

0

Okay, so you have a random string the user typed in ("a"). And you have a variable you call "a". There is no relationship between these.

The easiest solution is a series of if-statements.

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.

1 Comment

What is the purpose of this if/else statement, if you always call a.getName()?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.