简体   繁体   中英

How can I change a string to integer to use in a for loop

I have been doing C++ but recently I started doing a bit more on C# Windows Form Application and I'm making a program where you input a number and it flips a coin that amount of times. This is my code so far:

    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);
        }
    }

What am I doing wrong?

I see two problems in your code.

First, if your user types something that is not an integer number (or doesn't type anything at all) then Parse call will throw an exception and it is best practice avoid the exception if you can.

Second, the for loop, loops on time too much, you start from zero and stops at the limit less 1

So you could change your code to

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++)
    {
         ....

EDIT
Just noticed another problem in this line

   randomizer = rnd.Next(1,2);

as MSDN says the parameters for the Next call are the minValue and the maxValue, but maxValue should be

The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.

So if you want random numbers between 1 and 2 included you should write

   randomizer = rnd.Next(1,3);

I would suggest not to work with the string. I would take a bool. Take the input string and convert it as soon as possible to bool like:

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

Then write a boolean Flip function:

bool Flip(bool value) ...

And then put the result back as string:

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

This keeps your logic separate from input and output and avoids this kind of problems even if calculations increase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM