LordCommanderMay
LordCommanderMay

Reputation: 54

C# why am I getting this output? output is writing object names more then once

Im making a simple D&D Battle Program. I'm trying to get the program to make random amount objects named enemy. which I think I accomplished but when I console.writeline the list of enemies I get doubles of the same object?

namespace ConsoleApp2
{
public class Enemy
{

    int HP = Tool.RandomNum(5, 20);

    public static int currentEnemies;
    public string Name = "Enemy ";


}
public static void CreateEnemies(int NumberOfEnemies)

List<Enemy> Enemieslist = new List<Enemy>();
int EnemyName=0;
while (NumberOfEnemies>0)
{                     
    NumberOfEnemies--;
    EnemyName++;
    Enemieslist.Add (new Enemy { Name = "Enemy " + (EnemyName) });
    foreach  (var Enemy in Enemieslist)
    {
      Console.WriteLine(Enemy.Name);
    }
      Enemy.currentEnemies++;


}
static void Main(string[] args)
{
    Tool.CreatePlayers();
    Tool.CreateEnemies(Tool.RandomNum(1,10));           //Tool.RandomNum(Highest Possible Value, Lowest)
    Console.WriteLine("{0} Enemies Approach...", Enemy.currentEnemies);
    Console.WriteLine("{0} Fighters Stands Ready...", Player.currentPlayers); 
}

Outputs:

  how many Players? 1
  Player 1 what is you name? Ragnar
  Enemy 1
  Enemy 1
  Enemy 2
  Enemy 1
  Enemy 2
  Enemy 3
  Enemy 1
  Enemy 2
  Enemy 3
  Enemy 4
  Enemy 1
  Enemy 2
  Enemy 3
  Enemy 4
  Enemy 5
  Enemy 1
  Enemy 2
  Enemy 3
  Enemy 4
  Enemy 5
  Enemy 6
  Enemy 1
  Enemy 2
  Enemy 3
  Enemy 4
  Enemy 5
  Enemy 6
  Enemy 7
  7 Enemies Approach...
  1 Fighters Stand Ready...
  Press any key to continue . . .

it seems like the program is making the correct amount of enemy but writing their names multiple times.

Upvotes: 0

Views: 58

Answers (2)

paparazzo
paparazzo

Reputation: 45096

You have a loop in a loop

while (NumberOfEnemies > 0)
{
    foreach  (var Enemy in Enemieslist)
    {
       Console.WriteLine(Enemy.Name);
    }
}

In the while loop you are writing every Enemy.Name which is the output you are getting.

public static void CreateEnemies(int NumberOfEnemies) is missing { }

Upvotes: 1

jamheadart
jamheadart

Reputation: 5303

Looks like you've got the writeline statement to indicate the enemy name written in the wrong place - it's writing for all enemies after you create the first enemy - where all enemies just = "Enemy 1"

but then it's writing again for all enemies after you create the 2nd.. "Enemy1, Enemy2"

then again for 3rd.. then for 4th

Each time it creates an enemy it's writing out the entire list of enemies.

Upvotes: 0

Related Questions