Home > Mobile >  Print dice using asterisk
Print dice using asterisk

Time:04-08

I doing a school activity and we need to get 2 random numbers and display them with a dice image using an asterisk. The problem is that it does not display the output that I expect.

Here's the code:

            int i, j;

            Console.Write("PRESS ENTER TO GENERATE RANDOM NUMBER.......\n\n");
            Console.ReadKey();
            Random ramnum = new Random();
            int dice = ramnum.Next(1, 7); //First random number 
            int die = ramnum.Next(1, 7);  //second random number
            Console.WriteLine("Dice 1: \t"   dice);
            Console.WriteLine("Dice 2: \t"   die);
            Console.WriteLine(" ");//separate the number and asterisk

            //first number asterisk
            
                for (i = 1; i <= dice; i  )
            {
                Console.Write("*"); //print asterisk for first number

            }
            Console.Write(" ");//space between to two asterisk

            //second number asterisk
            for (j = 1; j <= die; j  )
            { 
                    Console.Write("*"); //prints at border place
                }
             

        }
    }
}

The result:

Dice 1:         1
Dice 2:         3

 * ***

The desire output:

Dice 1:         5
Dice 2:         6

 *** ***
 **  ***
```none
Dice 1:         4
Dice 2:         3

 *** **
     **
```none
Dice 1:         1
Dice 2:         2

 *  **

CodePudding user response:

If this is the desired output

Dice1: 2
Dice2: 3

|*    |   |    *|
|     |   |  *  |
|    *|   |*    |

Then use the power of C# and define a Dice object which generates each dice with a random value and uses ToString() of text output.

Dice.cs

public class Dice
{
    static readonly Random rng = new Random();

    public Dice()
    {
        Roll();
    }

    public void Roll()
    {
        Value = rng.Next(1, 7);
    }
    public int Value { get; private set; }

    // Produce value number of asterisks 
    public override string ToString()
    {
        //            
  •  Tags:  
  • c#
  • Related