lundi 13 août 2018

For loop that doesn't iterate completely but displays no error message

I have a simple program that uses Random and a for loop to generate two six-digit numbers. The loop generates two numbers every time and most of the time both numbers are six digits. Sometimes, though, one of those numbers is less than 6 digits (4 to 5 digits). It generates no error message in all cases. What's going on? I've posted all the code although some of it is unused/tested until I can figure out the Random problem.

The six-digit number starts as an empty string. Random generates an integer, the integer gets converted to string then += onto six-digit number string, which is converted to an integer when the method finishes.

The rest of the program is unimplemented and will involve extracting the 2nd, 4th, and 6th place digits in each number and adding them all together. The troubling thing is the Random issue.

static void Main(string[] args)
{
    Numbers theNumbers = new Numbers();
    Console.WriteLine(string.Join(",", theNumbers.Ints[0]));
    Console.WriteLine(string.Join(",", theNumbers.Ints[1]));
}

Numbers class

class Numbers
{
    public int[] Ints { get; set; }
    public char[][] TheNumbers { get; set; } //unused as of yet

    public Numbers()
    {
        Ints = new int[5];
        TheNumbers = new char[2][];//unused
        CreateTheFirstTwoNumbers(new RandomNummberGenerator());
        ConvertAllNumbersToCharacterArrays(); //unused. Removing this line had no effect on outcome.
    }

    public int[] CreateTheFirstTwoNumbers(RandomNummberGenerator RNG) 
    {
        for (int arrayIndex = 0; arrayIndex < 2; arrayIndex++)
        {
            Ints[arrayIndex] = RNG.CreateRandomNumber();
        }

        return Ints;
    }

    public void ConvertAllNumbersToCharacterArrays() //unused
    {
        for (int i = 0; i < TheNumbers.Length; i++)
        {
            TheNumbers[i] = ConvertNumberToCharacterArray(i);
        }
    } 

    public char[] ConvertNumberToCharacterArray(int indexOfIntergerSource)//unused
    {
        return Ints[indexOfIntergerSource].ToString().ToCharArray();
    }

Random Number Generator class

class RandomNummberGenerator
{
    public Random  Generator { get; set; }

    public RandomNummberGenerator()
    {
        Generator = new Random();
    }

    public int CreateRandomNumber()
    {
        string number = "";

        for (int numberIndex = 0; numberIndex < 6; numberIndex++)
        {
            number += Generator.Next(0, 10).ToString();
        }

        return int.Parse(number);
    }
}




Aucun commentaire:

Enregistrer un commentaire