-1

I created a few objects in main class and bounded with NPC class.

NPC zagolar = new NPC("Zagolar",25000,25000,250,50);
NPC riginmon = new NPC("Riginmon",50000,50000,500,100);
NPC setkov = new NPC("Schetkov",100000,100000,1000,150);
NPC tortugate = new NPC("Tortugate",200000,200000,2000,200);
NPC echonia = new NPC("Echonia",225000,225000,2500,400);
NPC cajsa = new NPC("Cajsa",250000,250000,2750,500);
NPC vaula = new NPC("Vaula",300000,300000,3500,700);

I want to choose currentNPC from one of them randomly. Can you help me about it?

Serhat
  • 31
  • 4
  • 2
    Add them to an array or a list and then pick a random index. – Keiwan Jan 15 '17 at 09:41
  • 1
    A very concise answer, add all of them to a list and then use `NPC randomItem = list.get(new Random().nextInt(list.size()))` – Naman Jan 15 '17 at 09:50
  • Thank you so much, question might be simple but I'm the new one in programming. – Serhat Jan 15 '17 at 09:58
  • In other words, use the solution from [this answer: Randomly select an item from a list](http://stackoverflow.com/questions/12487592/randomly-select-an-item-from-a-list) – Ole V.V. Jan 15 '17 at 10:15
  • Depending on taste, may instead use an array and a solution from [this answer: How to randomly pick an element from an array](http://stackoverflow.com/questions/8065532/how-to-randomly-pick-an-element-from-an-array). It will work for an array of `NPC` objects too. – Ole V.V. Jan 15 '17 at 10:16

1 Answers1

1

I would use an array, because its probably faster than an ArrayList and it does not convert everything to Objects. So, initialize an array like that :

NPC[] random_npc=new NPC[] {zagolar,riginmon,setkov,tortugate,echonia,cajsa,vaula};

and then pick a random element :

NPC choosed_npc=random_npc[(int)(Math.random()*random_npc.length)];

(Math.random gives a number bigger than 0 and smaller than 1)

Luatic
  • 8,513
  • 2
  • 13
  • 34
  • Rather than `7` I would definitely use `random_npc.length`. It’s both easier to understand and less prone to get erroneous next time you change the code. Otherwise nice! – Ole V.V. Jan 15 '17 at 12:21
  • Thanks for suggestion. – Serhat Jan 15 '17 at 14:32