尝试用c#

时间:2015-10-07 02:54:50

标签: c# random

嗨,所以我是编程的新手,我刚开始上学,我想开始编程,所以请记住,我向你展示的一切都是自学成才。这是我的问题,我想做一个随机数字猜谜游戏,并且大多数情况下它可以工作,但每次你点击按钮来猜测randoms一个不同的数字,我不想在这里是我到目前为止

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    // number of guesses
    int numberOfGesses = 0;

    private void btnCalc_Click(object sender, EventArgs e)
    {
        // make the generator
        Random generator = new Random();

        //make the number
        int number = generator.Next(1, 10);


        // get the users guess
        int guess = int.Parse(txtInput.Text);

        //check the users guess
        if (guess == number)
        {
            lblAnswer.Text = "You got it";
            numberOfGesses = 0;
        }
        else if (guess != number)
        {
            numberOfGesses = numberOfGesses + 1;
            lblAnswer.Text = "try agian you have gessed" + (numberOfGesses) + " times";
        }

    }


}

我知道它会不断创建一个新号码,因为每次按下猜测按钮,它都会从顶部开始并创建一个新号码。我试图采用这个块并使其成为全局但我收到了错误

// make the generator
        Random generator = new Random();

        //make the number
        int number = generator.Next(1, 10);

再次我真的很新,我找到了这个网站,当我查找一些qeustions我有所以我认为这将是一个很好的地方,以帮助我学习编程,而我等到我可以进入编程课程谢谢你的时间

2 个答案:

答案 0 :(得分:1)

您可能会收到错误,因为C#不允许您根据其他字段指定字段的默认值。

public partial class Form1 : Form {
    int numberOfGuess = 0;
    Random generator = new Random();
    int number;

    // other methods
}

generator可以在number之前或之后初始化,因此会出错。相反,您可以将其放在表单intializer(Form1方法)中,或者创建另一个按钮并单击它并生成一个新的随机数:

public partial class Form1 : Form
{
    // number of guesses
    int numberOfGesses = 0;
    Random generator = new Random();
    int number;

    public Form1()
    {
        InitializeComponent();

        // Generate the random number
        number = generator.Next(1, 10);
    }

    private void btnRandom_Click(object sender, EventArgs e)
    {
        // Generate a new random number when you click a button on the form
        number = generator.Next(1, 10);
    }

    private void btnCalc_Click(object sender, EventArgs e)
    {
        // get the users guess
        int guess = int.Parse(txtInput.Text);

        //check the users guess
        if (guess == number)
        {
            lblAnswer.Text = "You got it";
            numberOfGesses = 0;
        }
        else if (guess != number)
        {
            numberOfGesses = numberOfGesses + 1;
            lblAnswer.Text = "try agian you have gessed" + (numberOfGesses) + " times";
        }
    }
}

答案 1 :(得分:0)

您不能使用实例变量初始化另一个实例变量。的为什么?因为编译器可以重新排列这些 - 不能保证生成器在数字之前被初始化,所以上面的行可能会抛出NullReferenceException。 因此,将默认数值更改为0:

Random generator = new Random();
int number = 0;

在构造函数中初始化:

 public Form1()
    {
        InitializeComponent();
        number = generator.Next(1, 10);
    }

单击按钮时会生成数字,因为此处您将需要它:

 private void btnCalc_Click(object sender, EventArgs e)
    {
                //take the input & Compare as before.
    }