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;
}
}
}
}
我的主要:
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);
}
}
}
当我尝试在MakeGuess中的if语句中检查它时,我的问题是_secretNumber总是0。
我该如何解决问题以便该程序有效?
答案 0 :(得分:3)
在Initialize中,您将其声明为方法变量。这仅存在于方法内部,并且优先于字段(aka this._secretNumber)。
而不是
// declares and assigns a method variable
int _secretNumber = ...
只需使用
// assigns the field
_secretNumber = ...
答案 1 :(得分:2)
您在此处重新声明了第二个_secretNumber
变量,该变量隐藏了_secretNumber
字段:
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);
}
答案 2 :(得分:0)
我想知道这怎么可能编译...... 你在Initialize()方法的范围内声明你的_secret号码,所以一旦你完成初始化,变量就会超出范围。
您应该将_secret号码声明为您班级范围内的私人字段。
干杯!