19

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?

David Basarab
  • 72,212
  • 42
  • 129
  • 156
arin
  • 602
  • 1
  • 6
  • 17

9 Answers9

48
string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
    answer[i]= Console.ReadLine();
}
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
9

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.

Coderer
  • 25,844
  • 28
  • 99
  • 154
  • after showing the user a msg to input the elements(6 floating numbers) I want the user to input the elements separeated by commas so at first i decleared the array double[] array; array = new double[6]; now i need to read the elements – arin Oct 23 '08 at 17:31
  • Your line `string[] tokens = foo.Split(",");` should be `string[] tokens = foo.Split(',');` Note the double quotes changed to single quotes. – Radmation May 02 '16 at 21:02
  • I got your code and My Example is solved but I can't understand your if statement. Please explain me it – Bhavin Mar 08 '22 at 14:04
4

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!

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

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();
Ed Altorfer
  • 4,373
  • 1
  • 24
  • 27
  • 0 No, I didnt mean a message box . i meant when I'm showing a msg console.writeline("enter the elements of the array"); so what i dont know how to do is how to take the series of inputs from the user using a for loop – arin Oct 23 '08 at 16:58
2

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.

Stefan
  • 1,719
  • 2
  • 15
  • 27
2

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;
        }
    }
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
arin
  • 602
  • 1
  • 6
  • 17
  • 1
    Congratulations for persevering :) I've edited the post *just* for the formatting of the first few lines, but left all the rest in place. Will add another comment in a sec with a few suggested changes. – Jon Skeet Oct 23 '08 at 19:40
  • Added a different answer instead - easier to express myself. – Jon Skeet Oct 23 '08 at 19:52
  • This is the best ever! It really helped me in a tight bunch. I made one small change. Put the Console.WriteLine("Please Sir Enter 6 Floating numbers"); inside the for loop. – GreenArrow Nov 12 '21 at 03:48
0

readline is for string.. just use read

0

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

Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76
0

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

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