0

C# - I'm trying to write an array which stores information from user input. In my code I use a string array which I named friends and then I proceed to use this method https://stackoverflow.com/a/230463/14764548. In the end I want the console app to display the stored information as an array.

enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace arraysTut
{
    class arraysTut
    {
        static void Main()

            string[] friends = new string[2];
            for(string i=0;i<friends.length;i++)
            {
                Console.WriteLine("First Friend: ");
                friends[i] = Console.ReadLine();
            
                Console.WriteLine("Second Friend: ");
                friends[i] = Console.ReadLine();
                
                Console.WriteLine(friends);

                Console.ReadLine();
            }
    }
}
  • Read your code out loud: Create an string array, length 2, indexes 0 and 1. Then loop twice (index=0 first time, then index=1). The first time through, you prompt for "1st Friend", take the result and put it in `friends[0]`,then you prompt again (2nd Friend) and then take that result and put it in `friends[0]`, overwriting what was there. Then you write `friends` to the console and wait for user input. But, friends is an array, and if you convert that to a string, all you get is the name of the type (a string array). Then you do it again, prompting twice and writing/overwriting `friends[1]` – Flydog57 Jan 22 '21 at 00:20

1 Answers1

1

Apart from a few minor issues, you were nearly there

var friends = new string[2];

for (var i = 0; i < friends.Length; i++)
{
   Console.Write($"Enter friend ({i + 1}) : ");
   friends[i] = Console.ReadLine();
}

Console.WriteLine();
Console.WriteLine("These are your friends");

foreach (var friend in friends)
   Console.WriteLine(friend);

Console.WriteLine("Game Over!");

Output

Enter friend (1) : bob
Enter friend (2) : john

These are your friends 
bob
john
Game Over!

It's worth noting, List<T> are good a match for these types of situations, you don't have to worry about indexes, and can just expand and add to the list with List.Add(something)

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • 1
    If you do use a `List`, you can enter N friends, not just two. What you do is you read `Console.ReadLine()` into a variable (say `var newFriendName = Console.ReadLine();`. If the variable is not `IsNullOrEmpty` (look it up), then you `friendsList.Add(newFriendName)`. If it is null or empty, then you figure the data entry is complete and break out of the first loop. – Flydog57 Jan 22 '21 at 00:25