Reputation: 79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _1DV402.S2.L04
{
class SecretNumber
{
// Fields
private int _count;
private int _secretNumber;
public const int MaxNumberOfGuesses = 7;
public SecretNumber()
{
//_count = 0;
//_secretNumber = 0;
Initialize();
}
public void Initialize()
{
// Randomize a number between 1-100.
Random random = new Random();
int _secretNumber = random.Next(1, 101);
Console.WriteLine(_secretNumber);
}
public bool MakeGuess(int number)
{
if(number > _secretNumber)
{
_count++;
Console.WriteLine("{0} is too high. You have {1} guesses left", number, MaxNumberOfGuesses - _count);
return false;
}
else if (number < _secretNumber)
{
Console.WriteLine("{0} is too low. You have {1} guesses left", number, _count);
return false;
}
else
{
Console.WriteLine("Congratulations. You did it {0}.", _count);
return true;
}
}
}
}
And my Main:
using System;
namespace _1DV402.S2.L04
{
class Program
{
static void Main(string[] args)
{
int number = 0;
SecretNumber secretNumber = new SecretNumber();
Console.WriteLine(new String('*', 40));
Console.Write("Gissar på 0 ");
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine("(ska inte bli rätt!)");
Console.ResetColor();
secretNumber.MakeGuess(0);
Console.WriteLine(new String('*', 40));
do
{
secretNumber.Initialize();
Console.WriteLine("\nGissa ett tal mellan 1-100");
for (int i = 1; i <= SecretNumber.MaxNumberOfGuesses; i++)
{
do
{
Console.Write("Gissning {0}: ", i);
} while (!int.TryParse(Console.ReadLine(), out number));
if (secretNumber.MakeGuess(number))
{
break;
}
}
Console.Write("Nytt hemligt nummer? [N] avbryter.");
} while (Console.ReadKey(true).Key != ConsoleKey.N);
}
}
}
My problem is _secretNumber is allways 0 when i try to check it in my if-statements in MakeGuess.
how can i solve the problem so the program works?
Upvotes: 1
Views: 453
Reputation: 20792
i wonder how could this possibly compile... you declare your _secret number within the scope of your Initialize() method, so the variable goes out of scope as soon as you're finished with initialization.
You should declare the _secret number as a private field, within the scope of your class.
Cheers!
Upvotes: 0
Reputation: 54764
You're re-declaring a second _secretNumber
variable here, which hides the _secretNumber
field:
public void Initialize()
{
// Randomize a number between 1-100.
Random random = new Random();
int _secretNumber = random.Next(1, 101);
// ^^^
// Should be:
// _secretNumber = random.Next(1, 101);
Console.WriteLine(_secretNumber);
}
Upvotes: 2
Reputation: 1064184
In Initialize you are declaring it as a method variable. This only exists inside the method, and takes precedence over the field (aka this._secretNumber).
Rather than
// declares and assigns a method variable
int _secretNumber = ...
Just use
// assigns the field
_secretNumber = ...
Upvotes: 3