Home > Net >  Error 'enemytype' is not null here & use of unassigned variable 'enemytype'
Error 'enemytype' is not null here & use of unassigned variable 'enemytype'

Time:12-05

using static System.Console;
int enemy;
string enemytype;
string Juggernaut, Swiftster, Samurai;
Random random = new Random();

int d6 = random.Next(0, 6);
int d5 = random.Next(1, 5);
int d4 = random.Next(1, 4);
int d3 = random.Next(1, 3);
WriteLine("Welcome to the... DICE DOME! Your battle begins NOW! Press any key to roll the magical 3 sided dice to determine who you'll be fighting:");
ReadKey();
enemy = d3;
if (enemy == 1)
{
    enemytype = "Juggernaut";
}
else if (enemy == 2)
{
    enemytype = "Swiftster";
}
else if (enemy == 3)
{
    enemytype = "Samurai";
}
else
{
    //
}

WriteLine("=====================================================================");
WriteLine("You rolled a "   d3   ", you will be battling "   enemytype   "!");
WriteLine("=====================================================================");

I'm expecting enemytype in the last line to read out either Juggernaut, Swiftster or Samurai but all I get is two errors. I've tried changing the string to a value and changing the if statements to if else if else statements. I'm not sure how to get it all working correctly. The only error is the unassigned variable and enemytype is not null here errors.

CodePudding user response:

The problem is that you've defined the enemytype variable as a string, but you're not initializing it with a value. This means that the variable is unassigned when you try to use it in the WriteLine() statement at the end of your code, which is causing the error you're seeing.

To fix this issue, you can initialize the enemytype variable with an empty string ("") at the beginning of your code, like this:

int enemy;
string enemytype;   // Declare enemytype without initializing it
string Juggernaut, Swiftster, Samurai;
Random random = new Random();

int d6 = random.Next(0, 6);
int d5 = random.Next(1, 5);
int d4 = random.Next(1, 4);
int d3 = random.Next(1, 3);
WriteLine("Welcome to the... DICE DOME! Your battle begins NOW! Press any key to roll the magical 3 sided dice to determine who you'll be fighting:");
ReadKey();
enemy = d3;
if (enemy == 1)
{
    enemytype = "Juggernaut";
}
else if (enemy == 2)
{
    enemytype = "Swiftster";
}
else if (enemy == 3)
{
    enemytype = "Samurai";
}
else
{
    enemytype = "";  // Initialize enemytype with an empty string
}

WriteLine("=====================================================================");
WriteLine("You rolled a "   d3   ", you will be battling "   enemytype   "!");
WriteLine("=====================================================================");

I hope this helps! Let me know if you have any other questions.

  • Related