Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
So here is the problem, i'm making a project that has this objectives:

make the following app.
 
  1. The data unit of the app, is a Student class with the following attributes
    . ID, No., Name, Age
    
  2. Menu with 4 options
    1- op1 - Create student (collects data from a student)
    Note: for a Person object and adds it to the collection or array of objects
    2- op2 - Student list (shows collection or array data on the screen)
    3- op3 - Save (stores the collection or array in a binary file)
    4- op4 - Load (reads the collection or array from the binary file and shows on the screen)
    
  3. Evaluation:
    1. Create 5 Students
    2. Save and close the program
    3. Booting and Loading Data * /


This are the Steps and objectives of my project. So here is my actual question:
- When i try to create a student for my student list, whenever i create a new one it always occupies the 1st Index of the array 0, so i can only create 1 student. I will paste the code bellow, the problem is somewhere in Case "1" of Switch.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

/*Teste: elaborar a seguinte app.
 
  1. A unidade de dados da app, é uma classe Aluno com os seguintes atributos
    . ID,Nº,Nome, idade
    
  2. Menu com 4 opções
    1- op1 - Cria aluno (recolhe os dados de um aluno)
    Nota: para um objeto Pessoa e adiciona à collection ou array de objetos
    2- op2 - Lista alunos  (mostra os dados da collection ou array no ecrã)
    3- op3 - Save (guarda a collection ou array numa file binária)
    4- op4 - Load (lê a collection ou array da file binária e mostra no ecrã)
    
  3. Avaliação:
    1. Criar 5 Alunos
    2. Salvar e fechar o programa
    3. Arrancar e Load dos Dados*/

namespace Cap07_TestePratico
{
    class Program
    {
        static void Main(string[] args)
        {
            Aluno[] arrayAluno = new Aluno[5];  //Cria 3 (pointers) referências a Classe Pessoa

            //Declaração dos objetos, aloca-os na memória
            arrayAluno[0] = new Aluno();
            arrayAluno[1] = new Aluno();
            arrayAluno[2] = new Aluno();
            arrayAluno[3] = new Aluno();
            arrayAluno[4] = new Aluno();

            //Criação e atribuição das variáveis
            string titulo = "MENU"; string opcao1 = "1- Cria Aluno"; string opcao2 = "2- Lista Aluno"; string opcao3 = "3- Save"; string opcao4 = "0- para sair";string opcao5 = "4- Load";

            //Chamada do método
            desenhaMenu(titulo, opcao1, opcao2, opcao3, opcao4,opcao5,arrayAluno);
        }

        /// <summary>
        /// Desenha um menu com titulo e 3 opções e 1 opção de saida
        /// </summary>
        /// <param name="titulo">Titulo do menu</param>
        /// <param name="opt1">1ª opção</param>
        /// <param name="opt2">2ª opção</param>
        /// <param name="opt3">3ª opção</param>
        /// <param name="opt4">Opção de saida</param>
        static void desenhaMenu(String titulo, String opt1, String opt2, String opt3, String opt4,String opt5,Aluno[] arrayAluno)
        {
            string opcaoo;

            //String fileAndLocation = "D:\\Users\\a49240\\Desktop\\testeC.bin";
            String fileAndLocation = "C:\\Users\\Hugo\\Desktop\\testeC.bin";

            //Faz
            do
            {
                //Criação e atribuição das variáveis
                int tamanho = titulo.Length;
                int tamanho1 = opt1.Length;
                int tamanho2 = opt2.Length;
                int tamanho3 = opt3.Length;
                int tamanho4 = opt4.Length;
                int tamanho5 = opt5.Length;

                //contagem de contador até 50
                for (int contador = 0; contador < 50; contador++)
                {
                    System.Console.Write(" ");  //Imprime um espaço
                }

                #region LINHA DE CIMA DO MENU

                //contagem de i até 20
                for (int i = 0; i < 20; i++)
                {
                    System.Console.Write("*" + " ");    //Imprime um * e um espaço
                }

                System.Console.WriteLine(); //Imprime uma linha em branco

                System.Console.Write(" ");  //Imprime 1 espaço

                #endregion

                #region CENTRA O TITULO
                //Contagem de i até 49
                for (int i = 1; i <= 49; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã 1 espaço
                }

                System.Console.Write("*");  //Imprime no ecrã um *

                //contagem de i até 18 - tamanho/2
                for (int i = 1; i <= 18 - tamanho / 2; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã um espaço
                }

                System.Console.Write(titulo);  //Imprime no ecrã o titulo

                //contagem de i até 18 - tamanho/2
                for (int i = 1; i <= 18 - tamanho / 2; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã 1 espaço
                }

                //Caso o tamanho seja par
                if (tamanho % 2 == 0)
                {
                    System.Console.Write(" ");  //Imprime no ecrã um espaço
                }

                System.Console.WriteLine("*");  //Imprime no ecrã um asterisco

                #endregion

                #region CAIXA DO MENU
                //contagem de i até 2
                for (int i = 0; i < 2; i++)
                {
                    //Contagem de contador até 50
                    for (int contador = 0; contador < 50; contador++)
                    {
                        System.Console.Write(" ");  //Imprime um espaço
                    }

                    System.Console.Write("*" + " ");  //Imprime um asterisco + um espaço

                    //contagem de k até 20
                    for (int k = 2; k < 20; k++)
                    {
                        System.Console.Write("  "); //Imprime no ecrã 2 espaços
                    }

                    System.Console.WriteLine("*");  //Imprime um asterisco
                }

                //contagem de contador até 50
                for (int contador = 0; contador < 50; contador++)
                {
                    System.Console.Write(" ");  //Imprime um espaço
                }

                //contagem de i até 20
                for (int i = 0; i < 20; i++)
                {
                    System.Console.Write("*" + " ");    //Imprime no ecrã um asterisco mais um espaço
                }

                System.Console.WriteLine(); //Imprime uma linha em branco

                #endregion

                #region parte lateral do menu

                //contagem de i até 3
                for (int i = 2; i < 3; i++)
                {
                    //Contagem de contador até 50
                    for (int contador = 0; contador < 50; contador++)
                    {
                        System.Console.Write(" ");  //Imprime um espaço
                    }

                    System.Console.Write("*" + " ");  //Imprime no ecrã um asterisco e um espaço

                    //contagem de k até 20
                    for (int k = 2; k < 20; k++)
                    {
                        System.Console.Write("  "); //Imprime no ecrã 2 espaços
                    }

                    System.Console.WriteLine("*");  //Imprime no ecrã um asterisco
                }

                #endregion

                #region 1ª opção

                //Contagem de i até 49
                for (int i = 1; i <= 49; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã um espaço
                }

                System.Console.Write(" ");  //Imprime um espaço

                System.Console.Write("*");  //Imprime um asterisco

                System.Console.Write("  ");

                System.Console.Write(opt1);  //Imprime no ecrã a 1ª opção

                //Contagem de i até 5 - tamanho1
                for (int i = 1; i <= 34 - tamanho1; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã 1 espaço
                }

                System.Console.Write(" ");

                System.Console.WriteLine("*");  //Imprime um asterisco

                #endregion

                #region 2ª opção

                //Contagem de i até 49
                for (int i = 1; i <= 49; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã um espaço
                }

                System.Console.Write(" ");  //Imprime um espaço

                System.Console.Write("*");  //Imprime um asterisco

                System.Console.Write("  ");

                System.Console.Write(opt2);  //Imprime no ecrã a 2ª opção

                //Contagem de i até 34 - tamanho1
                for (int i = 1; i <= 34 - tamanho2; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã 1 espaço
                }

                System.Console.Write(" ");

                System.Console.WriteLine("*");  //Imprime um asterisco

                #endregion

                #region 3ª opção

                //Contagem de i até 49
                for (int i = 1; i <= 49; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã um espaço
                }

                System.Console.Write(" ");  //Imprime um espaço

                System.Console.Write("*");  //Imprime um asterisco

                System.Console.Write("  ");

                System.Console.Write(opt3);  //Imprime no ecrã a 3ª opção

                //Contagem de i até 34 - tamanho1
                for (int i = 1; i <= 34 - tamanho3; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã 1 espaço
                }

                System.Console.Write(" ");

                System.Console.WriteLine("*");  //Imprime um asterisco

                #endregion

                #region 3ª opção

                //Contagem de i até 49
                for (int i = 1; i <= 49; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã um espaço
                }

                System.Console.Write(" ");  //Imprime um espaço

                System.Console.Write("*");  //Imprime um asterisco

                System.Console.Write("  ");

                System.Console.Write(opt5);  //Imprime no ecrã a 3ª opção

                //Contagem de i até 34 - tamanho1
                for (int i = 1; i <= 34 - tamanho5; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã 1 espaço
                }

                System.Console.Write(" ");

                System.Console.WriteLine("*");  //Imprime um asterisco

                #endregion

                #region 4ª opção

                //Contagem de i até 49
                for (int i = 1; i <= 49; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã um espaço
                }

                System.Console.Write(" ");  //Imprime um espaço

                System.Console.Write("*");  //Imprime um asterisco

                System.Console.Write("  ");

                System.Console.Write(opt4);  //Imprime no ecrã a 4ª opção

                //Contagem de i até 34 - tamanho1
                for (int i = 1; i <= 34 - tamanho4; i++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã 1 espaço
                }

                System.Console.Write(" ");

                System.Console.WriteLine("*");  //Imprime um asterisco

                #endregion

                #region centra e faz a linha de baixo do menu

                //Contagem de contador até 50
                for (int contador = 0; contador < 50; contador++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã 1 espaço
                }

                //Contagem de i até 20
                for (int i = 0; i < 20; i++)
                {
                    System.Console.Write("*" + " ");  //Imprime no ecrã o asterisco e um espaço
                }

                System.Console.WriteLine(); //Imprime uma linha em branco

                #endregion

                #region Centra e faz "Digite a opção" e switch

                //Contagem de contador até 50
                for (int contador = 0; contador < 50; contador++)
                {
                    System.Console.Write(" ");  //Imprime no ecrã um espaço
                }


                //Pede recebe e converte a opção escolhida pelo utilizador
                System.Console.Write("Digite a opção: ");
                opcaoo = System.Console.ReadLine();
                //opcao = Convert.ToInt32(opcaoo);

                //Verifica o valor de opcaoo
                switch (opcaoo)
                {
                    case "1":
                        Console.Clear();    //Limpa a consola
                        Console.WriteLine("Opção 1 Escolhida");    //Imprime no ecrã "Opção 1 escolhida"
                        //Da set a todos os IDs dos alunos
                        arrayAluno[0].setId(1);
                        arrayAluno[1].setId(2);
                        arrayAluno[2].setId(3);
                        arrayAluno[3].setId(4);
                        arrayAluno[4].setId(5);

                        //Pede o numero,nome e idade dos 5 alunos, recebe-os e usa os setters para os definir
                        for (int i = 0; i < 5; i++)
                        {
                            Console.WriteLine("Insira o numero de processo do aluno");
                            arrayAluno[i].setNumeroDeProcesso(Convert.ToInt32(Console.ReadLine()));

                            Console.WriteLine("Insira o nome do aluno");
                            arrayAluno[i].setNome(Console.ReadLine());

                            //Pede a idade do aluno, restringe caso a idade seja menor que 0 ou maior que 20
                            do
                            {
                                Console.WriteLine("Insira a sua idade");
                                arrayAluno[i].setIdade(Convert.ToInt32(Console.ReadLine()));
                            } while (arrayAluno[i].getIdade() < 0 || arrayAluno[i].getIdade() > 20);

                            Console.Clear();    //Limpa a consola
                            break;
                        }
                        break;

                    case "2":
                        Console.Clear();    //Limpa a consola

                        //Imprime os dados dos 5 alunos
                        for (int i = 0; i < 5; i++)
                        {
                            Console.WriteLine(arrayAluno[i].dizOla());
                        }
                        break;

                    case "3":
                        Console.Clear();    //Limpa a consola

                        // Serializar:
                        // Objeto Pessoa -> Serialização -> file
                        Serializar(fileAndLocation, arrayAluno);
                        break;

                    case "4":
                        Console.Clear();    //Limpa a consola

                        //Notificação de que a desSerializaçao correu bem
                        Console.WriteLine("DesSerializado para " + fileAndLocation);

                        //DesSerializar:
                        // File binária -> DesSerialização ->
                        // -> Casting (Conversão para o objeto final) -> Outro Objeto Pessoa
                        Aluno[] arrayAluno99 = (Aluno[])(DesSerializar(fileAndLocation));

                        //Imprime os dados dos 5 alunos
                        for (int i = 0; i < 5; i++)
                        {
                            Console.WriteLine(arrayAluno99[i].dizOla());
                        }
                        break;

                    case "0":
                        System.Console.Clear();             //Limpa a consola
                        System.Console.WriteLine("Você saiu");  //Imprime no ecrã "Voce saiu"
                        System.Console.WriteLine("Clique para avançar");    //Imprime no ecrã "Clique para avançar"
                        System.Console.ReadKey();           //So quando o utilizador clicar é que avança
                        System.Console.Clear();             //Limpa a consola
                        System.Environment.Exit(0);         //Fecha a consola
                        break;

                    default:
                        System.Console.Clear();             //Limpa a consola
                        System.Console.WriteLine("A opção esta errada introduza denovo");    //Imprime no ecrã "Ole"
                        System.Console.WriteLine("Clique para avançar");    //Imprime no ecrã "Clique para avançar"
                        System.Console.ReadKey();           //So quando o utilizador clicar é que avança
                        System.Console.Clear();             //Limpa a consola
                        break;
                }
                #endregion
            } while (opcaoo != "0"); //Enquanto a opcao for diferente de 0
        }

        /// <summary>
        /// Método para Serializar
        /// Serializa qualquer objeto, desde que a sua Classe seja serializável
        /// Para isso tem que ser preparada com "implements java.io.Serializable"
        /// Ordena os bits do objeto num formato próprio para ser enviado para a file.
        /// </summary>
        /// <param name="fileLocaton">string com a localização e nome da file onde será gravado o objeto</param>
        /// <param name="obj">Objeto a serializar (Object é o topo da hierarquia dos objetos nas POO)</param>
        static void Serializar(string fileLocaton, Object obj)
        {
            //Tentativa de serializar. Caso ocorra uma Exceção, é apanhada nos catchs
            try
            {
                // Cria um canal para a file em modo de escrita
                Stream streamToFile = File.OpenWrite(fileLocaton);

                // Cria o objeto de serialização (em C# é o mesmo da desSerialização)
                BinaryFormatter serializer = new BinaryFormatter();

                // Serialização: Convertem o Object para uma stream binária que grava na file
                serializer.Serialize(streamToFile, obj);

                // Encerramento do canal para a file.
                streamToFile.Close();

                // Notificação de que a serialização correu bem.
                Console.WriteLine("Objeto Serializado para " + fileLocaton);
            }
            catch (IOException e)
            {
                System.Console.WriteLine("ERRO: Impossivel criar ou abrir o ficheiro: ");
                System.Console.WriteLine(e.Message); // imprime o erro técnico
            }
            catch (Exception e)
            {
                System.Console.WriteLine("ERRO: Ocorreu um erro inesperado: ");
                System.Console.WriteLine(e.Message); // imprime o erro técnico
            }
        }

        /// <summary>
        /// Método para DesSerializar
        /// Recolhe o Object que estiver guardado na file binária
        /// </summary>
        /// <param name="fileLocation">string com a localização e nome da file a ser lida</param>
        /// <returns>Um objeto (topo da hierarquia das classes)</returns>
        static Object DesSerializar(string fileLocation)
        {
            try
            {
                // Cria um canal para a file em modo de leitura
                Stream streamFromFile = File.OpenRead(fileLocation);    // Cria Stream para abrir e ler da file

                // Cria o objeto DesSerialização (em C# é o mesmo da Serialização)
                BinaryFormatter desSerializer = new BinaryFormatter();

                // DesSerialização - Converte a stream binária da file para o formato Object
                Object obj = desSerializer.Deserialize(streamFromFile);

                // Encerramento do canal para a file.
                streamFromFile.Close();

                // Notificação de que a serialização correu bem
                //Console.WriteLine("Objeto DesSerializado para: " + fileLocation);

                return obj;
            }
            catch (IOException e)
            {
                System.Console.WriteLine("ERRO: Impossivel aceder ao ficheiro");
                System.Console.WriteLine(e.Message);    // imprime o erro técnico
                return null;                            // Se erro, devolve um objeto null
            }
            catch (Exception e)
            {
                System.Console.WriteLine("ERRO: Ocorreu um erro inesperado");
                System.Console.WriteLine(e.Message); // imprime o erro técnico
                return null;                        // Se erro, devolve um objeto null
            }
        }
    }
}



(The comments are in Portuguese)

Edit: Thanks for the answers, i made a question here a week ago or something with another problem, and OriginalGrieff told me about Debbuging at the time i didn't give it much importance but now i can see how important it his to have this skill. Thank you all i'll put some effort in learning it

However in this case i know what my code is doing, and what it is suposed to do , but i don't really know how to fix it.


What I have tried:

Observation: Im still a beginner so try to make it simple. But if it is a harder solution i have no problem at all learning it.
Posted
Updated 11-Oct-18 10:20am
v6

Compiling does not mean your code is right! :laugh:
Think of the development process as writing an email: compiling successfully means that you wrote the email in the right language - English, rather than German for example - not that the email contained the message you wanted to send.

So now you enter the second stage of development (in reality it's the fourth or fifth, but you'll come to the earlier stages later): Testing and Debugging.

Start by looking at what it does do, and how that differs from what you wanted. This is important, because it give you information as to why it's doing it. For example, if a program is intended to let the user enter a number and it doubles it and prints the answer, then if the input / output was like this:
Input   Expected output    Actual output
  1            2                 1
  2            4                 4
  3            6                 9
  4            8                16
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
C#
private int Double(int value)
   {
   return value * value;
   }

Once you have an idea what might be going wrong, start using the debugger to find out why. Put a breakpoint on the first line of the method, and run your app. When it reaches the breakpoint, the debugger will stop, and hand control over to you. You can now run your code line-by-line (called "single stepping") and look at (or even change) variable contents as necessary (heck, you can even change the code and try again if you need to).
Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
Hopefully, that should help you locate which part of that code has a problem, and what the problem is.
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
 
Share this answer
 
Quote:
- When i try to create a student for my student list, whenever i create a new one it always occupies the 1st Index of the array 0, so i can only create 1 student. I will paste the code bellow, the problem is somewhere in Case "1" of Switch.

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]
Debugging C# Code in Visual Studio - YouTube[^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900