如何将字符串更改为整数以在for循环中使用

时间:2015-11-26 19:13:51

标签: c#

我一直在做C ++,但最近我开始在C#Windows Form Application上做更多的事情,我正在制作一个程序,你输入一个数字,它会翻转硬币很多次。到目前为止,这是我的代码:

    private void flipCoin_Click(object sender, EventArgs e)
    {
        Random rnd = new Random();
        String HorT;
        int randomizer;
        for (int i = 0; i <= int.Parse(flipCoin.Text); i++)
        {
            randomizer = rnd.Next(1, 2);
            if (randomizer == 1)
            {
            HorT = "Heads";
            }
            else
            {
            HorT = "Tails";
            }
            richTextBox1.AppendText(Environment.NewLine + HorT);
        }
    }

我做错了什么?

2 个答案:

答案 0 :(得分:0)

我在你的代码中看到两个问题。

首先,如果您的用户键入的内容不是整数(或者根本不输入任何内容),那么Parse调用将抛出异常,如果可以,最好避免异常。

第二,for循环,循环时间过多,从零开始并停在极限值1

因此您可以将代码更改为

private void flipCoin_Click(object sender, EventArgs e)
{
    Random rnd = new Random();
    String HorT;
    int randomizer;
    int count;

    // Int32.TryParse return false if the input is not an integer
    if(!Int32.TryParse(flipCoin.Text, out count))
    {
         MessageBox.Show("Please type an integer number");
         return;
    }

    // Loop until the indexer is less than the limit       
    for (int i = 0; i < count); i++)
    {
         ....

修改
刚刚注意到这一行中的另一个问题

   randomizer = rnd.Next(1,2);

正如MSDN所说,Next调用的参数是minValue和maxValue,但maxValue应该是

  

返回的随机数的独占上限。 maxValue必须   大于或等于minValue。

因此,如果你想要1到2之间的随机数包括,你应该写

   randomizer = rnd.Next(1,3);

答案 1 :(得分:0)

我建议不要使用字符串。我会采取一个布尔。取输入字符串并尽快转换为bool,如:

bool HorT = false;
if (input=="Head") HorT =true;

然后写一个布尔翻转函数:

bool Flip(bool value) ...

然后将结果作为字符串返回:

string output = "Head";
if (HorT==true) output ="Tail";

这可以使您的逻辑与输入和输出分开,并且即使计算量增加也可以避免此类问题。