I would like to check in the customer register if the code entered already exists. How do I?

Asked

Viewed 575 times

0

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AtFinal
{
    class Program
    {

        struct Cliente
        {
            public int cod_cli;
            public string nome, endereco, telefone;
        }

        struct Recebimento
        {
            public decimal valorDoc;
            public DateTime dataEmissao, dataVencimento;
        }

        public static void Main(string[] args)
        {
            Cliente[] clientes = new Cliente[5];
            Recebimento[] recebimentos = new Recebimento[15];

            int qtdCliente = 0;
            int qtdRecebimento = 0;
            int opcao = -1;

            do
            {
                Console.Title = " * SISTEMA DE RECEBIMENTOS * ";
                Console.BackgroundColor = ConsoleColor.White;// Muda a cor da tela.
                Console.ForegroundColor = ConsoleColor.DarkBlue;// Muda a cor da letra.
                Console.Clear(); //limpa a tela

                //Imprime na tela as opções do Menu:
                Console.WriteLine("-------------------------");
                Console.WriteLine("     MENU DE OPÇÕES      ");
                Console.WriteLine("-------------------------");
                Console.WriteLine(" Informe a opção deseja: \n");
                Console.WriteLine("1. Cadastrar Cliente");
                Console.WriteLine("2. Alterar Cliente");
                Console.WriteLine("3. Cadastrar Recebimento");
                Console.WriteLine("4. Sair");
                Console.SetCursorPosition(25, 3); //Move o cursor para o fim da 4a linha

                //lê a opção escolhida pelo usuário
                opcao = Convert.ToInt32(Console.ReadLine());

                //limpa a tela
                Console.Clear();


                //direciona o programa para a opção escolhida pelo usuário:
                switch (opcao)
                {
                    case 1:
                    //Testa se já chegou ao limite de clientes cadastrados
                    //onde o limite é o tamanho (Length) do vetor:
                    if (qtdCliente < clientes.Length)
                    {
                        //Preenche os dados do cliente
                        Console.WriteLine("Digite os dados do cliente \n");
                        Console.Write("Código: ");
                        clientes[qtdCliente].cod_cli = Convert.ToInt32(Console.ReadLine());
                        Console.Write("Nome: ");
                        clientes[qtdCliente].nome = Console.ReadLine();
                        Console.Write("Endereço: ");
                        clientes[qtdCliente].endereco = Console.ReadLine();
                        Console.Write("Telefone: ");
                        clientes[qtdCliente].telefone = Console.ReadLine();

                        //incrementa o número de clientes
                        qtdCliente++;

                        Console.WriteLine("\nCliente Cadastrado com sucesso!");
                    }
                    else
                    {
                        Console.WriteLine("Número máximo alcançado: " + qtdCliente);
                    }

                    Console.Write("\nPressione qualquer tecla para voltar ao menu.");

                    //Aguarda o usuário pressionar qualquer tecla para continuar:
                    Console.ReadKey();
                    break;
                    case 2:
                        Console.WriteLine(" vazio ");
                        Console.ReadKey();
                        break;
                    case 3:
                        //Testa se já chegou ao limite de Recebimentos cadastrados
                        //onde o limite é o tamanho (Length) do vetor:
                        if (qtdRecebimento < recebimentos.Length)
                        {
                            //Preenche os dados dos Recebimentos
                            Console.WriteLine("Digite os dados dos Recebimentos \n");
                            Console.WriteLine("Número do documento: " + (qtdRecebimento + 1));
                            Console.Write("Valor R$: ");
                            recebimentos[qtdRecebimento].valorDoc = Convert.ToDecimal(Console.ReadLine());
                            Console.Write("Data de emissão: ");
                            recebimentos[qtdRecebimento].dataEmissao = Convert.ToDateTime(Console.ReadLine());
                            Console.Write("Data de vencimento: ");
                            recebimentos[qtdRecebimento].dataVencimento = Convert.ToDateTime(Console.ReadLine());

                            qtdRecebimento++;

                            Console.WriteLine("\nRecebimento cadastrado com sucesso!");
                        }
                        else
                        {
                            Console.WriteLine("Número máximo já alcançado: " + qtdRecebimento);
                        }

                        Console.Write("\nPressione qualquer tecla para voltar ao menu.");

                        //Aguarda o usuário pressionar qualquer tecla para continuar:
                        Console.ReadKey();
                        break;
                    case 4:
                        Console.Title = " * SAIR * ";
                        Console.WriteLine("------------------");
                        Console.WriteLine("Saindo do Sistema");
                        Console.WriteLine("------------------");
                        Console.ReadKey();
                        break;

                    default: //executado quando o usuário escolhe uma opção que não existe
                        Console.Title = " * INVALIDO * ";
                        Console.WriteLine("---------------");
                        Console.WriteLine("Opção inválida!");
                        Console.WriteLine("---------------");
                        Console.Write("\nPressione qualquer tecla para voltar ao menu.");
                        //Aguarda o usuário pressionar qualquer tecla para continuar:
                        Console.ReadKey();
                        break;
                }
            } while (opcao != 4);
        }
    }
}
  • Dude, I really don’t know what your need is. But asking the user to indicate a numeric code that should be unique will never be a good idea. I’m sorry, but what is the real need for this? This information will be persisted in a database or stored only until the application is finalized?

  • will not be stored, will only be used until the application is finished. We are not using database, it is an application of type Console. I modified the field code not to be entered by the user but automatically generated. But I need to take this "code" field of the customer to use it in Receipt... because it is through it that I can verify how many receipts there are per customer... understand? Because each customer can only have 3 receipts associated...

  • Got it, thanks for clarifying. As soon as I have a spare time I will assist you, if no one has done it yet.

  • Thank you very much, this is an end-of-term job. It consists of, using the following records, do: CLIENT -cod_cli -name -end -tel RECEIVING -numDoc -data_outgoing -data_venc -cod_cli a) Include Receiving (check if customer is already registered); b) change Customer Registration (User must inform cod_cli q will be changed); c) Show all Receipts with expiration date within any period. Show the customer’s name and the total number of days overdue, if zero; d) You can only register a maximum of 3 receipts per customer.

  • So far @Brunobermann, no one has helped me... :-(

  • Another @Brunobermann question is that for this activity we can only use: Struct, Subroutine, Pointers, Vector, and the old known Loop Repetition.

Show 1 more comment

1 answer

1


The simplest way is by using LINQ, which seems to already be ready to use. So you can do a simple query:

var codCli = Convert.ToInt32(Console.ReadLine()); //isso pode dar erro fácil
if (clientes.Contains(codCli)) {
    //aqui pede o resto dos dados
    clientes[qtdCliente].cod_cli = codCli;
    .
    .
    .
}

I put in the Github for future reference.

Documentation.

I just want to point out that I understand this is an exercise, but in a real application the code will be considered full of errors. It only works in very specific circumstances. Otherwise it lacks enough organization in it.

  • Thanks @bigown, I’ll try...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.