0

how do I print objects name randomly, for instance: skeleton, zombie or assassin ?

but all of em have used on class only Enemies ?

For example, I have:

Enemies skeleton = new Enemies(100, 20);
Enemies zombie = new Enemies(90, 30);
Enemies warrior = new Enemies(80, 40);
Enemies assassin = new Enemies(70, 30);

Enemies[] enemy = {skeleton, zombie, warrior, assassin};

I have tried:

int randEnemy = random.nextInt(enemy.length);

it gives me random number only, but I want to get the name of a object

  String name = random.nextInt(enemy.length);

from here I get error

System.out.println(enemy.getClass().getSimpleName());

but it gives me the name of Class "Enemy"

  • 6
    Anyway, you're probably better off adding a `name` string field to the `Enemies` (actually, following standard naming practices, it should be called `Enemy`) class and use that, something like `Enemy zombie = new Enemy(90, 30, "zombie");` so that later you can use something `zombie.getName()` to obtain "zombie" – Federico klez Culloca Oct 12 '20 at 13:31
  • Indeed, you should add a `name` field to your class. – Hulk Oct 12 '20 at 13:33
  • Under **exactly** the right circumstances, an `Enemies` could use Reflection to examine every variable that might point to it and ask "Is that me?" and thus come, indirectly, to figure out its name. Or, better yet, just do @FedericoklezCulloca's thing. – Kevin Anderson Oct 12 '20 at 13:41

2 Answers2

0

You could use reflection to obtain the variable names off of the heap or a neater soultion would be to use inherirence

class Zombie extends Enemies { }
Enemies zombie = new Zombie(90, 30);
...

That way the enemy.getClass().getSimpleName() method would return Zombie.

ScottFree
  • 582
  • 6
  • 23
-2

try

String name = enemy.getName());

or

System.out.println(enemy.getClass().getName());

Actualy solved here: How do I print the variable name holding an object?

  • 1
    FYI `enemy.getClass().getName()` will print the class name not object name. – Sudhir Ojha Oct 12 '20 at 13:36
  • 1
    The second one wouldn't really help with what the OP wants to achieve. And the first only helps if the `enemy` actually has a name field (it doesn't look like it has one, judging by the constructor call). – Hulk Oct 12 '20 at 13:36