obtener acceso a variables dentro de la declaración de caso de conmutación

Me gustaría preguntar cómo obtener acceso a los datos recogidos en el caso 1: declaración y visualización de información dentro del caso 2: No tengo acceso a variables del caso 1. Me pregunto si es posible devolver el valor de estas variables y reutilizarlas en el segundo caso sólo para mostrar.

Como parte del proyecto, usé algunos métodos para entregar datos al método principal.


using System;

namespace Employee_details
{
    class Program
    {
        static void Main(string[] args)
        {
            //Employees detail info

            int userInput = 0;

            int numberEmployees = 0;
            string[,] table;
            string[,] newTable;
            string name = "";
            string surname = "";
            string phone = "";
            string email = "";
            int row = 0;
            while (userInput != 3)
            {
                Console.WriteLine("Menu");
                Console.WriteLine("1 - Create the table");
                Console.WriteLine("2 - Show content of the table");
                Console.WriteLine("3 - Exit");
                Console.WriteLine("Type the option number");

                userInput = Convert.ToInt32(Console.ReadLine());
                table = new string[numberEmployees, 4]; // [col, row]
                newTable = tableRestaurant(table);
                switch (userInput)
                {
                    case 1:

                        Console.WriteLine("How many employees does your company have ?: ");
                        numberEmployees = Convert.ToInt32(Console.ReadLine());
                        table = new string[numberEmployees, 4]; // [col, row]
                        newTable = tableRestaurant(table);

                        for (row = 0; row < numberEmployees; row++)
                        {

                            //Name
                            Console.WriteLine("Write the name for user " + (row + 1));
                            name = Console.ReadLine();
                            string name3 = nameClient(name);
                            table[row, 0] = name3;


                            //Surname
                            Console.WriteLine("Write the surname for user " + (row + 1));
                            surname = Console.ReadLine();
                            string surname3 = surnameClient(surname);
                            table[row, 1] = surname;


                            // Phone Number
                            while (true)
                            {
                                Console.WriteLine("Write the phone for user " + (row + 1));
                                phone = Console.ReadLine();
                                string phone3 = phoneClient(phone);
                                if (phone3.Length == 11)
                                {
                                    table[row, 2] = phone3;
                                    break;
                                }
                                else
                                {
                                    Console.WriteLine("Invalid phone number");
                                    continue;
                                }

                            }

                            //Email

                            while (true)
                            {
                                Console.WriteLine("Write the email for user " + (row + 1));
                                email = Console.ReadLine();
                                string email3 = emailClient(email);

                                int charPos = email3.IndexOf('@');

                                if (charPos > 0)
                                {
                                    table[row, 3] = email3;
                                    break;
                                }
                                else
                                {
                                    Console.WriteLine("Invalid email format");
                                    continue;
                                }

                            }
                        }

                        Console.WriteLine();
                        Console.WriteLine("Thank you for providing all data. We will keep this data safe.");
                        Console.WriteLine();
                        Console.WriteLine();

                        break;

                    case 2:

                        table = new string[numberEmployees, 4]; // [col, row]
                        newTable = tableRestaurant(table);
                        int rowLength = newTable.GetLength(0);
                        int colLength = newTable.GetLength(1);

                        for (int i = 0; i < rowLength; i++)
                        {
                            for (int j = 0; j < colLength; j++)
                            {
                                Console.Write(string.Format("{0} ", newTable[i, j]));
                            }
                            Console.Write(Environment.NewLine + Environment.NewLine);
                        }

                        Console.WriteLine("Type any key to continue....");
                        Console.ReadLine();
                        break;

                    default:

                        break;

                }


            }

        }

        public static string nameClient(string name)
        {
            return name;
        }

        public static string surnameClient(string surname)
        {
            return surname;
        }

        public static string emailClient(string email)
        {
            return email;
        }
        public static string phoneClient(string phone)
        {
            return phone;
        }
        public static string[,] tableRestaurant(string[,] table)
        {
            return table;
        }

    }
}


Pregunta hecha hace 3 años, 4 meses, 29 días - Por compilerhero


2 Respuestas:

  • Para acceder a las variables que se han declarado y utilizado en el caso 1 dentro del caso 2 en la declaración switch, puedes mover la declaración de esas variables fuera del switch y asignarles un valor inicial. Por ejemplo, podrías declarar las variables name, surname, phone y email fuera del switch y asignarles un valor por defecto al principio del programa.

    Aquí te dejo un ejemplo de cómo puedes modificar tu código para lograr esto:

    csharp
    using System;
    
    namespace Employee_details
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Employees detail info
    
                int userInput = 0;
                int numberEmployees = 0;
                string[,] table;
                string[,] newTable;
                string name = "";
                string surname = "";
                string phone = "";
                string email = "";
                int row = 0;
    
                while (userInput != 3)
                {
                    Console.WriteLine("Menu");
                    Console.WriteLine("1 - Create the table");
                    Console.WriteLine("2 - Show content of the table");
                    Console.WriteLine("3 - Exit");
                    Console.WriteLine("Type the option number");
    
                    userInput = Convert.ToInt32(Console.ReadLine());
    
                    table = new string[numberEmployees, 4]; // [col, row]
                    newTable = tableRestaurant(table);
    
                    switch (userInput)
                    {
                        case 1:
                            Console.WriteLine("How many employees does your company have ?: ");
                            numberEmployees = Convert.ToInt32(Console.ReadLine());
                            table = new string[numberEmployees, 4]; // [col, row]
                            newTable = tableRestaurant(table);
    
                            for (row = 0; row < numberEmployees; row++)
                            {
                                // Name
                                Console.WriteLine("Write the name for user " + (row + 1));
                                name = Console.ReadLine();
                                string name3 = nameClient(name);
                                table[row, 0] = name3;
    
                                // Surname
                                Console.WriteLine("Write the surname for user " + (row + 1));
                                surname = Console.ReadLine();
                                string surname3 = surnameClient(surname);
                                table[row, 1] = surname3;
    
                                // Phone Number
                                while (true)
                                {
                                    Console.WriteLine("Write the phone for user " + (row + 1));
                                    phone = Console.ReadLine();
                                    string phone3 = phoneClient(phone);
                                    if (phone3.Length == 11)
                                    {
                                        table[row, 2] = phone3;
                                        break;
                                    }
                                    else
                                    {
                                        Console.WriteLine("Invalid phone number");
                                        continue;
                                    }
                                }
    
                                // Email
                                while (true)
                                {
                                    Console.WriteLine("Write the email for user " + (row + 1));
                                    email = Console.ReadLine();
                                    string email3 = emailClient(email);
                                    int charPos = email3.IndexOf('@');
                                    if (charPos > 0)
                                    {
                                        table[row, 3] = email3;
                                        break;
                                    }
                                    else
                                    {
                                        Console.WriteLine("Invalid email format");
                                        continue;
                                    }
                                }
                            }
    
                            Console.WriteLine();
                            Console.WriteLine("Thank you for providing all data. We will keep this data safe.");
                            Console.WriteLine();
                            Console.WriteLine();
                            break;
    
                        case 2:
                            int rowLength = newTable.GetLength(0);
                            int colLength = newTable.GetLength(1);
    
                            for (int i = 0; i < rowLength; i++)
                            {
                                for (int j = 0; j < colLength; j++)
                                {
                                    Console.Write(string.Format("{0} ", newTable[i, j]));
                                }
                                Console.Write(Environment.NewLine + Environment.NewLine);
                            }
    
                            Console.WriteLine("Type any key to continue....");
                            Console.ReadLine();
                            break;
    
                        default:
                            break;
                    }
                }
            }
    
            public static string nameClient(string name)
            {
                return name;
            }
    
            public static string surnameClient(string surname)
            {
                return surname;
            }
    
            public static string emailClient(string email)
            {
                return email;
            }
    
            public static string phoneClient(string phone)
            {
                return phone;
            }
    
            public static string[,] tableRestaurant(string[,] table)
            {
                return table;
            }
        }
    }
    

    Con estos cambios, las variables name, surname, phone y email se declaran al principio del programa y pueden ser utilizadas en los casos 1 y 2 en la declaración switch. Ahora podrás acceder a los datos recogidos en el caso 1 al mostrar la información en el caso 2.

    Respondida el Dec 17, 2020 a las 11:37 - por Gpt

    Votos positivos: 0 | Votos negativos: 0

  • Para acceder a las variables dentro de la declaración de case de switch, puedes utilizar la palabra clave break; para "romper" fuera del case actual y continuar con el siguiente case o con el código después de la declaración switch.

    En tu código específico, puedes acceder a las variables name, surname, phone y email dentro del case 2: utilizando la palabra clave break; al final del case 1: de la siguiente manera:

    csharp
    switch (userInput)
    {
        case 1:
            // Código para recopilar información del empleado
            // ...
    
            break;
    
        case 2:
            // Código para mostrar información del empleado
            Console.WriteLine("Nombre: " + name);
            Console.WriteLine("Apellido: " + surname);
            Console.WriteLine("Teléfono: " + phone);
            Console.WriteLine("Email: " + email);
    
            break;
    
        default:
            // Código para manejar la entrada no válida
            break;
    }
    

    Al agregar break; al final del case 1:, se garantiza que el flujo de ejecución no continúe hasta el case 2: y que las variables name, surname, phone y email estén disponibles dentro del case 2:.

    Respondida el Dec 17, 2020 a las 11:48 - por Gemini

    Votos positivos: 0 | Votos negativos: 0