-3

Hi as a student I have to create a "Rock-Paper-Scissors" game in Java.

The player chooses when creating a game if he wants to follow some pre-defined strategies like playing "Rock-Rock-Paper" for example and so I have an Interface to implements differents strategies like RockStrat() or PaperStrat().

When I create a game from the console the user is prompted to type in which strat he wants to follow, let's say, for instance he types in PaperStrat. His input is read and "PaperStrat" is saved as a String.

My problem here is I can't figure out how to go from a String to calling the class PaperStrat other than by having an IF condition for each strategy available but that seems way too sloppy.

Any help would be appreciated, Thanks.

dtlvd
  • 457
  • 1
  • 8
  • 21
Rémy.W
  • 225
  • 2
  • 9
  • [This](https://stackoverflow.com/questions/3434466/creating-a-factory-method-in-java-that-doesnt-rely-on-if-else) might help. – Andrew S Mar 27 '18 at 14:20

3 Answers3

2

You could use Reflections, which would be a very unclean way to do this and I would not recommend it, since it would be using a sledge-hammer to crack a nut.

The easiest way would be to use a String based switch statement like this:

switch (userInput) {
        case "RockStrat":
            //choose rock strat
            break;
        case "PaperStrat":
            //choose paper strat
            break;
        default:
            //choose default strat
            break;
}
0

Another conditional check that you might use is the switch control. You can switch check the String you're getting from the user input and create a case for each one. This way the code is more readable: Switch tutorial

Also consider that the question is generic and there are a whole lot of ways to do things in Java. Example: you might even use the Java Reflection mechanism to read the String argument and create the interface through a factory, but that way it's gonna become too much complex for such a trivial task.

Endrik
  • 2,238
  • 3
  • 19
  • 33
0

You should look into the datatructure hashmap, which maps a key to a value. A value can be of any kind. Including a object of a class.

\\fill
hmap.put("rock", rockObject);
hmap.put("scissor", scissorObject);
\\get
chosenAction = hmap.get(chosenString)'
nmanh
  • 325
  • 2
  • 14