2

I have this code where I input a name, and then an integer. The application will then repeat the name entered according to the integer specified. The issue i'm having is, I only want the user to be able to repeat the name a max of 10 times and and min of 1. Here is what i have thus far.

Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
string Name = Console.ReadLine();

Console.Write("Enter the number of times you wish for me to repeat your name, " + Name );
int number = Int32.Parse(Console.ReadLine());

for (int i = 0; i < number; i++)        
    Console.WriteLine(""+ Name);
Console.ReadKey();

EDIT: If someone sees an easier way of doing what I have, I would be happy to suggestions!

mrtig
  • 2,217
  • 16
  • 26

3 Answers3

1
 static void Main(string[] args)
    {
        Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
        string Name = Console.ReadLine();

        Console.Write("Enter the number of times you wish for me to repeat your name");
        var input = Console.ReadLine();
        int number = -1;
        while (!int.TryParse(input, out number)) {
            Console.WriteLine("Incorrect Value");
            Console.Write("Enter the number of times you wish for me to repeat your name");
            input = Console.ReadLine();
        }

        for (int i = 0; i < number; i++)
        {
            Console.WriteLine("" + Name);
            if (i == 9)
            {
                Console.WriteLine("End Program");
                break;
            }
       }

        Console.ReadKey();

    }
Saif
  • 2,611
  • 3
  • 17
  • 37
1

You need to filter and validate if the input number is minimum of 1, and maximum of 10, before printing the names. You can do this:

 Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: ");
        string Name = Console.ReadLine();

        Console.Write("Enter the number of times you wish for me to repeat your name, " + Name);

        int number = 0;

        do
        {
            Int32.TryParse(Console.ReadLine(), out number);
            if (number > 10 || number < 1)
                Console.WriteLine("Please input numbers between 1 to 10");

        } while (number > 10 || number < 1);

            for (int i = 0; i < number; i++)
                Console.WriteLine("" + Name);
        Console.ReadKey();

I am doing a do-while loop here. Unless the while loop is satisfied, it will continuously verify if the number is on the range specified or else it will exit and it will print the names.

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
0

You could wrap the ReadLine() in a while statement

Example being

int number = -1;
while(number < 1 || number > 10)
{
        //Input code
}
//for loop goes under here
KaSSii
  • 41
  • 3