Передать информацию о 2D-массиве в метод на c#

#c# #arrays #multidimensional-array #methods

#c# #массивы #многомерный массив #методы

Вопрос:

У меня есть оценка, в которой мы должны реализовать методы в приложении для хранения информации о сотрудниках в 2D-массиве и отображения ее на экране. Пока код работает нормально, но я не могу найти способ передать информацию о 2D-массиве в регистр 2 коммутатора. Это всегда приводит к исключению IndexOutOfRangeException, когда я пытаюсь вернуть информацию о массиве из метода userInput или при создании метода для случая 2 и попытке передать массив. Это код, который у меня есть, заранее спасибо за помощь:

 using System;

namespace EmployeeFileWithMethods
{
  class Program
  {
    static void Main(string[] args)
    {
      int numberEmployees = 0;
      string[,] table = new string[numberEmployees, 4];
      string userInput = "1";
      while ( userInput != "0" )
      {

        userInput = Intro();

        switch ( userInput )
        {
          case "1":
            UserInput();
            break;
          case "2":
            Console.Clear();
            for ( int user = 0; user < table.GetLength(0); user   )
            {
              Console.WriteLine("     User "   ( user   1 ));
              for ( int row = 0; row < table.GetLength(1); row   )
              {
                Console.Write(table[user, row]   "n");
              }
              Console.WriteLine("");
            }
            break;
          case "0":
            break;
          default:
          {
            DefaultCase();
            break;
          }

        }

      }
      Console.WriteLine("Thanks for using the app!");
      Console.ReadLine();
    }
    public static string Intro()
    {
      Console.WriteLine("[-------------------------------------------------------------------------------]");
      Console.WriteLine("                        Welcome to the Edinburgh College App n                             What would you like to do?n                                   1:Add Usern                                   2:Show User Infon                                   0:Exit");
      Console.WriteLine("[-------------------------------------------------------------------------------]");
      string userInput = Console.ReadLine();
      return userInput;
    }
    public static void DefaultCase()
    {
      Console.Clear();
      Console.WriteLine("[-------------------------------------------------------------------------------]");
      Console.WriteLine("              The option that you entered is invalid. Please try again.              ");
      Console.WriteLine("[-------------------------------------------------------------------------------]");
    }
    public static void UserInput()
    {
      Console.WriteLine("How many employees does your company have?");
      int numberEmployees = Convert.ToInt32(Console.ReadLine());
      string[,] table = new string[numberEmployees, 4];
      for ( int row = 0; row < numberEmployees; row   )
      {
        Console.WriteLine("Write the Forename of user "   ( row   1 ));
        string forename = Console.ReadLine();
        table[row, 0] = forename;
        Console.WriteLine("Write the Surname of user "   ( row   1 ));
        string surname = Console.ReadLine();
        table[row, 1] = surname;

        while ( true )
        {
          Console.WriteLine("Write the Phone of user "   ( row   1 ));
          string phone = Console.ReadLine();
          if ( phone.Length == 11 )
          {
            table[row, 2] = phone;
            break;
          }
          else
          {
            Console.WriteLine("Invalid Phone Number. Please Try Again");
            continue;
          }
        }
        while ( true )
        {
          Console.WriteLine("Write the Email of user "   ( row   1 ));
          string email = Console.ReadLine();
          int charPos = email.IndexOf('@');
          if ( charPos > 0 )
          {
            table[row, 3] = email;
            break;
          }
          else
          {
            Console.WriteLine("Invalid Email. Please Try Again");
            continue;
          }
        }

      }
    }
  }

}
 

Ответ №1:

Я не могу воспроизвести исключение, но UserInput ничего не возвращает, и таблица, инициализированная в этом методе, теряется при возврате. Таким Main образом, размер таблицы в первом dim равен 0. Вы должны передать таблицу в качестве параметра с помощью ref и удалить объявление таблицы в методе:

 UserInput(table);

public static void UserInput(ref string[,] table)
 

Но вам нужно изменить размер этого массива, чтобы добавить новые входные данные.

Лучший и более простой, надежный и чистый способ — использовать список объектов класса. Вот код, адаптированный и улучшенный для использования списка объекта employee. Я коснулся минимального кода, но его можно улучшить и переработать больше, особенно while циклы, а также вы можете использовать int.TryParse для добавления количества сотрудников.

 using System.Collections.Generic;
 
 public class Employee
{
  public string Forename { get; set; }
  public string Surname { get; set; }
  public string Phone { get; set; }
  public string Email { get; set; }
}
 
 static private void Main()
{
  var employees = new List<Employee>();
  string userInput = "1";
  while ( userInput != "0" )
  {
    userInput = Intro();
    switch ( userInput )
    {
      case "1":
        UserInput(employees);
        break;
      case "2":
        Console.Clear();
        for ( int index = 0; index < employees.Count; index   )
        {
          Console.WriteLine("     User "   ( index   1 ));
          Console.WriteLine("         Forename: "   employees[index].Forename);
          Console.WriteLine("         Surname: "   employees[index].Surname);
          Console.WriteLine("         Phone: "   employees[index].Phone);
          Console.WriteLine("         eMail: "   employees[index].Email);
          Console.WriteLine("");
        }
        break;
      case "0":
        break;
      default:
      {
        DefaultCase();
        break;
      }

    }

  }
  Console.WriteLine("Thanks for using the app!");
  Console.ReadLine();
}
 
 public static void UserInput(List<Employee> employees)
{
  Console.WriteLine("How many employees does your company have?");
  int countEmployees = employees.Count;
  int countEmployeesNew = Convert.ToInt32(Console.ReadLine());
  for ( int indexEmployeeNew = 0; indexEmployeeNew < countEmployeesNew; indexEmployeeNew   )
  {
    int posEmployeeNew = countEmployees   indexEmployeeNew   1;
    Console.WriteLine("Write the Forename of user "   posEmployeeNew);
    string forename = Console.ReadLine();
    Console.WriteLine("Write the Surname of user "   posEmployeeNew);
    string surname = Console.ReadLine();
    string phone = "";
    while ( true )
    {
      Console.WriteLine("Write the Phone of user "   posEmployeeNew);
      phone = Console.ReadLine();
      if ( phone.Length == 11 ) break;
      Console.WriteLine("Invalid Phone Number. Please Try Again");
    }
    string email = "";
    while ( true )
    {
      Console.WriteLine("Write the Email of user "   posEmployeeNew);
      email = Console.ReadLine();
      int charPos = email.IndexOf('@');
      if ( charPos > 0 ) break;
      Console.WriteLine("Invalid Email. Please Try Again");
    }
    employees.Add(new Employee
    {
      Forename = forename,
      Surname = surname,
      Phone = phone,
      Email = email
    });
  }
}