开发者

Clicking game - Operator '-' cannot be applied to operands of type 'string' and 'int' error

Iam making a clicking game, but there is an error i can't get working correctly. The error is: Operator '-' cannot be applied to operands of type 'string' and 'int'

in the private void timer1.tick. i have been looking on google and this site, but didnt manage to find a compareable error. i've tried the longer minus and the short minus sign.

(made in visual c# 2010 express)

public partial class Form1 : Form
{
    int timeLeft;
    int counter = 10;



    public Form1()
    {
        InitializeComponent();
    }


    private void timer1_Tick(object sender, EventArgs e)
    {
          timer1.Interval = 1000;
          timeLabel.Text = timeLabel.Text - 1;




        {
            if (timeLeft > 0)
            {
                timeLeft--;
                timeLabel.Text = timeLeft + " seconds";
            }
            else
            {
开发者_开发百科                timer1.Stop();
                timeLabel.Text = "Score";

                MessageBox.Show(Score.Text, "Score");

                Plus.Enabled = false;
            }
        }
    }

    private void Plus_Click(object sender, EventArgs e)
    {
        timer1.Start();
        Score.Text = Score.Text + 1;
        Score.Text = counter.ToString();
    }



}


Score.Text is a string; you can't subtract a number from a string. You have to convert the string to a number before you can do math on it.

Note that Score.Text + 1 doesn't do math; the + operator concatenates strings, rather than doing arithmetic.


My recommendation - don't use the timeLabel to store the "truth" about the time remaining.

Instead, do something like:

timeLeft--;
if (timeLeft > 0)
{
   timeLabel.Text = timeLeft + " seconds";
}
else
{
   timer1.Stop();
   timeLabel.Text = "Score");
}

The error is telling you that there's no operator- that takes an int there - essentially, whatever operator- means for the class, in this case string, it doesn't know what to do with an integer argument.

Again, don't do it that way. You've already got the integer value. The timeLabel is a presentation thing, the timeLeft int is a business logic piece. Let the timeLabel do what it does best - showing text to the user - and let the integer field, timeLeft manage what the new seconds value should be.

Same thing with your score text. You're mixing presentation and business logic here. Just make an int for your score and then do something like:

Score.Text = currentScore.ToString();

As an aside, the Score.Text line in Plus_Click probably doesn't work as you intend. I'm assuming Score is a text box or something like that. It's not going to show whatever Score.Text + 1 is because it's going to be overwritten by whatever counter.ToString() is. Not trying to beat on you here, just pointing it out.


timeLabel.Text = Int32.Parse(timeLabel.Text) - 1;

Likewise in other places. HTH.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜