1

当我运行它并玩游戏时,每次只生成数字 0。你能帮我弄清楚问题是什么吗?

public partial class MainPage : PhoneApplicationPage
{
    int numberguessed;
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        int numberguessed = randnum.Next(0,1000);
    }



    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        myTextBlock.Text = " No worries ! Go again .. ";
        myTextbox.Text = "";
        myTextbox.Focus();
    }

    private void myButton2_Click(object sender, RoutedEventArgs e)
    {
        //string sval = myTextbox.Text;
        int ival = System.Convert.ToInt32(myTextbox.Text);
        if (ival == numberguessed)
            myTextBlock.Text = " You won ";
        else if (ival < numberguessed)
            myTextBlock.Text = "Your guess is too low !";
        else if (ival > numberguessed)
            myTextBlock.Text = "Your guess is too high !";
    }

    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
        myTextbox.Focus();
    }
4

3 回答 3

4

在这部分

public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        int numberguessed = randnum.Next(0,1000);
    }

您通过在其前面加上“int”来覆盖您的顶级 numberguessed 变量。将其更改为:

public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        numberguessed = randnum.Next(0,1000);
    }
于 2013-09-13T08:55:58.870 回答
4

您声明numberguessedfield,然后在 中重新声明一个新的局部int numberguessed变量MainPage()。在其他方法中,field将使用该值。由于它没有被初始化,它将具有 int 的默认值,0。

int numberguessed;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Random randnum = new Random();
            //remove int there like this
            //int numberguessed = randnum.Next(0,1000);
           numberguessed = randnum.Next(0,1000);
        }

顺便说一句,你应该有一个警告(或者可能只是更清楚地这样做)说明

局部变量 numberguessed 隐藏字段 .MainPage.numberguessed

于 2013-09-13T08:56:29.993 回答
0

改变这部分

int numberguessed;
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        int numberguessed = randnum.Next(0,1000);
    }

 private int numberguessed;
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        numberguessed = randnum.Next(0,1000);
    }

问题是,一旦你在类中声明你的字段/属性,然后int numberguessed在构造函数中再次声明创建一个类似的字段。后一个字段仅保留在构造函数内部的范围内,并在构造函数结束后消失。但是,所有 int 字段的默认值为 0,并且您正在访问的字段是在类之外定义的字段。因此,您只得到一个默认值。

于 2013-09-13T09:14:29.800 回答