简体   繁体   中英

display user input from do while loop C#

I have some code below that is almost finished, but the last thing I want to do is for the console app to display the number they have gotten from the user

EX: if user input 1, 3, 5 the console will display

The number you have inserted are:

  1. One

  2. Three

  3. Five

Is it possible to do that?

Thanks

static void Main (string []args)
        {
            string again;
            do
            {
                Console.Clear();
                Console.WriteLine("Insert Random number");
                int number = int.Parse(Console.ReadLine());

                Console.WriteLine("Would you like to Insert another number ?(Enter Y for yes /Enter any other key to exit)");
               again = Console.ReadLine();
            } while (again == "Y");


            Console.WriteLine("The number you have inserted are: ");


            Console.ReadKey();
        }

First, you need a place to keep all the numbers you collected. Given this code, you may be expected to use an array , but real code is more likely to use a generic List<int> . Declare it near the beginning of the Main method like this:

List<int> numbers = new List<int>();

Add each number to it after Parse()-ing like this:

numbers.Add(number);

Then, in between the final WriteLine() and ReadKey() calls, you need to loop through the collected numbers:

int i = 0;
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine($"{i+1}. {numbers[i]}");
}

What you won't be able to do in a simple way is convert the digit 1 to the text value One . There's nothing built into C# or.Net to do that part for you. Since this code looks like a learning exercise, I'll leave you to attempt that part on your own.

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