C#卡路里计数器

1 c# exception string-parsing

我是编程新手,并且刚开始学习第一门课程,即编程基础知识,而在目前的家庭作业中,我遇到了一个我无法解决的问题。

问题是-“一袋饼干可容纳40个饼干。袋中的卡路里信息声称袋中有10份,每份等于300卡路里。创建一个应用程序,让用户输入自己或他或她的Cookie数量她实际上吃了,然后报告了所消耗的卡路里数量。”

我的表格: 我的表格

我在未调试的情况下运行时遇到的错误: 未经调试运行时出现的错误

//下面是我的代码

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            int cookies = int.Parse(textBox1.Text);

            int calories = (cookies * 75);

            textBox2.Text = calories.ToString();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Sac*_*ach 5

You encounter this problem when using the int.Parse() method. This method simply converts whatever you passed to it as a string to int. So, something like "33" will be converted, but what if you entered something that is clearly not an integer such as "x" or even an empty string?

So, this will be converted to a value of 33 in int type no problem.

int parseResultGood = int.Parse("33");
Run Code Online (Sandbox Code Playgroud)

But this will fail and throw an exception, because, obviously "x" cannot be converted into an integer.

int parseResultBad = int.Parse("x");
Run Code Online (Sandbox Code Playgroud)

Luckily though, C# provides you another method to handle this better, namely, int.TryPrase() method. As the name suggests it tries to parse the value, and converts it into an int only if it is possible and send it back to you in the out parameter while it will return true. If the conversion failed, say, because you passed a non-integer value as a string, it will return false, and the value of the out parameter will be zero. So based on the return value of true/false you can know if the conversion was successful or not, and it won't thrown an exception.

int tryParseResult = 0;
if (int.TryParse("X", out tryParseResult))
{
    // Use the converted value
}
else
{
    // Display an error message or something similar
}
Run Code Online (Sandbox Code Playgroud)

However, I suggest you learn to debug your program. If you did, you'd have been able to figure out the problem for yourself. The article that was linked to in comments is a great one, please follow it. Good luck!

  • +1清晰的答案。如果可以的话,我将其分开,并将其放在另一个私有函数的另一个类中,以便使用click事件将应用程序的逻辑分开。然后单击将调用该函数,并使应用程序更整洁。 (2认同)