[c#] How to Fill an array from user input C#?

What would be the best way to fill an array from user input?

Would a solution be showing a prompt message and then get the values from from the user?

This question is related to c#

The answer is


C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.

If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:

using Microsoft.VisualBasic;

You can do the following:

List<string> responses = new List<string>();
string response = "";

while(!(response = Interaction.InputBox("Please enter your information",
                                        "Window Title",
                                        "Default Text",
                                        xPosition,
                                        yPosition)).equals(""))
{
   responses.Add(response);
}

responses.ToArray();

readline is for string.. just use read


It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...

1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.

2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.

3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);

to this:

for (int counter = 0; counter < 6; counter++)
{
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}

It makes the block clearer, and means you don't accidentally write:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
    Console.WriteLine("----"); // This isn't part of the for loop!

4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:

bool keepGoing = true;
while (keepGoing)
{
    switch (answer)
    {
        case "yes":
            Console.WriteLine("===============================================");
            Console.WriteLine("please enter the array index you wish to get the value of it");
            int index = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("===============================================");
            Console.WriteLine("The Value of the selected index is:");
            Console.WriteLine(array[index]);
            keepGoing = false;
            break;

        case "no":
            Console.WriteLine("===============================================");
            Console.WriteLine("HAVE A NICE DAY SIR");
            keepGoing = false;
            break;

        default:
            Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
            break;
    }
}

5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:

// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();

Again, this is fairly advanced - don't worry about it for now!


I've done it finaly check it and if there is a better way tell me guys

    static void Main()
    {
        double[] array = new double[6];
        Console.WriteLine("Please Sir Enter 6 Floating numbers");
        for (int i = 0; i < 6; i++)
        {
            array[i] = Convert.ToDouble(Console.ReadLine());
        }

        double sum = 0;

        foreach (double d in array)
        {
            sum += d;
        }
        double average = sum / 6;
        Console.WriteLine("===============================================");
        Console.WriteLine("The Values you've entered are");
        Console.WriteLine("{0}{1,8}", "index", "value");
        for (int counter = 0; counter < 6; counter++)
            Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
        Console.WriteLine("===============================================");
        Console.WriteLine("The average is ;");
        Console.WriteLine(average);
        Console.WriteLine("===============================================");
        Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
        string answer = Console.ReadLine();
        switch (answer)
        {
            case "yes":
                Console.WriteLine("===============================================");
                Console.WriteLine("please enter the array index you wish to get the value of it");
                int index = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("===============================================");
                Console.WriteLine("The Value of the selected index is:");
                Console.WriteLine(array[index]);
                break;

            case "no":
                Console.WriteLine("===============================================");
                Console.WriteLine("HAVE A NICE DAY SIR");
                break;
        }
    }

Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.

If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use

string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
    if(Int32.TryParse(s, out oneNum))
        nums.Add(oneNum);
}

Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.


Try:

array[i] = Convert.ToDouble(Console.Readline());

You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.


Add the input values to a List and when you are done use List.ToArray() to get an array with the values.


C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.

If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:

using Microsoft.VisualBasic;

You can do the following:

List<string> responses = new List<string>();
string response = "";

while(!(response = Interaction.InputBox("Please enter your information",
                                        "Window Title",
                                        "Default Text",
                                        xPosition,
                                        yPosition)).equals(""))
{
   responses.Add(response);
}

responses.ToArray();

Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.

If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use

string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
    if(Int32.TryParse(s, out oneNum))
        nums.Add(oneNum);
}

Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.


Try:

array[i] = Convert.ToDouble(Console.Readline());

You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.


Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.

If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use

string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
    if(Int32.TryParse(s, out oneNum))
        nums.Add(oneNum);
}

Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.


Try:

array[i] = Convert.ToDouble(Console.Readline());

You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.


C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.

If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:

using Microsoft.VisualBasic;

You can do the following:

List<string> responses = new List<string>();
string response = "";

while(!(response = Interaction.InputBox("Please enter your information",
                                        "Window Title",
                                        "Default Text",
                                        xPosition,
                                        yPosition)).equals(""))
{
   responses.Add(response);
}

responses.ToArray();

of course....Console.ReadLine always return string....so you have to convert type string to double

array[i]=double.Parse(Console.ReadLine());


Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.

If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use

string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
    if(Int32.TryParse(s, out oneNum))
        nums.Add(oneNum);
}

Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.


I've done it finaly check it and if there is a better way tell me guys

    static void Main()
    {
        double[] array = new double[6];
        Console.WriteLine("Please Sir Enter 6 Floating numbers");
        for (int i = 0; i < 6; i++)
        {
            array[i] = Convert.ToDouble(Console.ReadLine());
        }

        double sum = 0;

        foreach (double d in array)
        {
            sum += d;
        }
        double average = sum / 6;
        Console.WriteLine("===============================================");
        Console.WriteLine("The Values you've entered are");
        Console.WriteLine("{0}{1,8}", "index", "value");
        for (int counter = 0; counter < 6; counter++)
            Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
        Console.WriteLine("===============================================");
        Console.WriteLine("The average is ;");
        Console.WriteLine(average);
        Console.WriteLine("===============================================");
        Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
        string answer = Console.ReadLine();
        switch (answer)
        {
            case "yes":
                Console.WriteLine("===============================================");
                Console.WriteLine("please enter the array index you wish to get the value of it");
                int index = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("===============================================");
                Console.WriteLine("The Value of the selected index is:");
                Console.WriteLine(array[index]);
                break;

            case "no":
                Console.WriteLine("===============================================");
                Console.WriteLine("HAVE A NICE DAY SIR");
                break;
        }
    }

It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...

1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.

2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.

3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);

to this:

for (int counter = 0; counter < 6; counter++)
{
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}

It makes the block clearer, and means you don't accidentally write:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
    Console.WriteLine("----"); // This isn't part of the for loop!

4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:

bool keepGoing = true;
while (keepGoing)
{
    switch (answer)
    {
        case "yes":
            Console.WriteLine("===============================================");
            Console.WriteLine("please enter the array index you wish to get the value of it");
            int index = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("===============================================");
            Console.WriteLine("The Value of the selected index is:");
            Console.WriteLine(array[index]);
            keepGoing = false;
            break;

        case "no":
            Console.WriteLine("===============================================");
            Console.WriteLine("HAVE A NICE DAY SIR");
            keepGoing = false;
            break;

        default:
            Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
            break;
    }
}

5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:

// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();

Again, this is fairly advanced - don't worry about it for now!


Add the input values to a List and when you are done use List.ToArray() to get an array with the values.


It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments...

1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.

2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment.

3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);

to this:

for (int counter = 0; counter < 6; counter++)
{
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}

It makes the block clearer, and means you don't accidentally write:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
    Console.WriteLine("----"); // This isn't part of the for loop!

4) Your switch statement doesn't have a default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:

bool keepGoing = true;
while (keepGoing)
{
    switch (answer)
    {
        case "yes":
            Console.WriteLine("===============================================");
            Console.WriteLine("please enter the array index you wish to get the value of it");
            int index = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("===============================================");
            Console.WriteLine("The Value of the selected index is:");
            Console.WriteLine(array[index]);
            keepGoing = false;
            break;

        case "no":
            Console.WriteLine("===============================================");
            Console.WriteLine("HAVE A NICE DAY SIR");
            keepGoing = false;
            break;

        default:
            Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
            break;
    }
}

5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:

// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();

Again, this is fairly advanced - don't worry about it for now!


of course....Console.ReadLine always return string....so you have to convert type string to double

array[i]=double.Parse(Console.ReadLine());


readline is for string.. just use read


Try:

array[i] = Convert.ToDouble(Console.Readline());

You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.


I've done it finaly check it and if there is a better way tell me guys

    static void Main()
    {
        double[] array = new double[6];
        Console.WriteLine("Please Sir Enter 6 Floating numbers");
        for (int i = 0; i < 6; i++)
        {
            array[i] = Convert.ToDouble(Console.ReadLine());
        }

        double sum = 0;

        foreach (double d in array)
        {
            sum += d;
        }
        double average = sum / 6;
        Console.WriteLine("===============================================");
        Console.WriteLine("The Values you've entered are");
        Console.WriteLine("{0}{1,8}", "index", "value");
        for (int counter = 0; counter < 6; counter++)
            Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
        Console.WriteLine("===============================================");
        Console.WriteLine("The average is ;");
        Console.WriteLine(average);
        Console.WriteLine("===============================================");
        Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
        string answer = Console.ReadLine();
        switch (answer)
        {
            case "yes":
                Console.WriteLine("===============================================");
                Console.WriteLine("please enter the array index you wish to get the value of it");
                int index = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("===============================================");
                Console.WriteLine("The Value of the selected index is:");
                Console.WriteLine(array[index]);
                break;

            case "no":
                Console.WriteLine("===============================================");
                Console.WriteLine("HAVE A NICE DAY SIR");
                break;
        }
    }