DEV Community

Kiron Roy
Kiron Roy

Posted on • Updated on

C# Looping through first names

This was some forgotten homework. I did write a program that "worked", but it didn't follow the guidelines (I used a case statement and an array). This small C# console application gave me some trouble. Fortunately, found a helpful stackoverflow link that helped me get unstuck.

On Repl.it

using System;
using System.Collections.Generic;
// https://stackoverflow.com/questions/28596078/adding-multiple-user-input-to-a-list-c-sharp

namespace CoreyForeach_Better
{
    class Program
    {
        static void Main(string[] args)
        {
            // Ask user for their first name
            // continue asking for the first names until there are no more
            // loop through each name and tell them hello

            List<string> firstNamesList = new List<string>();

            Console.WriteLine("What is your first name?");
            string firstNamesInput = Console.ReadLine();
            firstNamesList.Add(firstNamesInput);

            while (firstNamesInput != "")
            {
                Console.WriteLine("Please add another name, or just press enter to see list of names");
                firstNamesInput = Console.ReadLine();
                if(firstNamesInput !="") 
                {
                  firstNamesList.Add(firstNamesInput);
                }
            }
            if (firstNamesInput == "")
            {
                foreach (string firstnames in firstNamesList)
                {
                    Console.WriteLine(firstnames);
                }
            }



            Console.ReadLine();

        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
softchris profile image
Chris Noring • Edited on

It looks like your code allows for an empty first name to be added when the user press the enter key. imo, it should look like this:

while (firstNamesInput != "")
            {
                Console.WriteLine("Please add another name, 
                                 or just press enter to see list of names");
                firstNamesInput = Console.ReadLine();
                if(firstNamesInput !="") 
                {
                  firstNamesList.Add(firstNamesInput);
                }
            }
            if (firstNamesInput == "")
            {
                foreach (string firstnames in firstNamesList)
                {
                    Console.WriteLine(firstnames);
                }
            }

            Console.ReadLine();
Collapse
kironroy profile image
Kiron Roy Author

Thanks, Chris. I forgot to check for that scenario!