C# Object reference not defined for an object instance

Asked

Viewed 101 times

2

Who can help me and explain this problem I will be grateful

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

namespace BuscaLargura
{
   partial class Program
    {
        static void Main(string[] args)
        {

            /* Node grafos = Grafo();
             Console.WriteLine(" ");
             bfs_transversal(grafos);*/
            List<Node> listanos = new List<Node>();
            List<Node> conectados = new List<Node>();
            String[] text = System.IO.File.ReadAllLines(@"C:\Users\Pedro Pacheco\Desktop\Mapa.txt");
            for (int i = 0; i < text.Length; i++)
            {
                if (text[i].Contains("city"))
                {
                    //Console.WriteLine(text[i][5]);
                    listanos.Add(new Node(text[i][5]));//adiciona um Nó com o nome da 5 posição da linha do Mapa.txt
                }
            }
            for (int i = 0; i < text.Length; i++)
            {
                if (text[i].Contains("route"))
                {
                    Console.WriteLine(text[i][6]);
                    for (int nopai = 0; nopai < listanos.Count; nopai++)//varrendo os nós sem conexão
                    {
                        if (listanos[nopai].data == text[i][6])//verificando se o Nó.data é igual a  text[i][6] ( exemplo= route=A)
                        {
                            for (int nofilho = 0; nofilho < listanos.Count; nofilho++)
                            {                                
                                if (listanos[nofilho].data == text[i][8])
                                {
                                    Console.WriteLine(text[i][8]);
                                    //listanos[nopai].conectados.Add(new Node(listanos[nofilho]));
                                    conectados.Add(listanos[nofilho]);
                                }

                            }
                                listanos[nopai].conectados.AddRange(conectados);  
                                conectados.Clear();
                        }                      
                    }
                }
            }

        }
    }
}

Node class:

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

namespace BuscaLargura { 

  public class Node { 

    public List<Node> conectados; 

    public char data;

    public Node(char data,List<Node> conectados)
    {
        this.conectados = conectados;
        this.data = data;
    }
    public Node(char data)
    {
        this.data = data;
    }
    public Node (List<Node> filhos)
    {
        this.conectados.AddRange(filhos);
    }
  }
}

Erro

  • Without the definition of class Node makes it difficult to help you. If you decide to publish the Ode class, mark my name (with arroba) so that I can be notified. Hence I give you a force.

  • 1

    @Augustovasques Pronto

  • My intention is after I create these listings, for each of this list to assign to another list of connected

  • connected public list; you sent it down there: public List conectados; would not be public List<Node> conectados;?

  • It was wrong because it did not find Mapa.txt????

  • Map is reading perfectly

  • Mine here, it’s not working because I don’t have that file. I need it

  • where I can make this map available ?

  • Edit the post and pass either a link from it on an online file system (github type) or if it is short put in the edit itself.

  • Or just pass a fragment of it that works and generates the same error that is giving there with you.

  • 1

    I posted the Map @Augustovasques but this divided by lines

  • Agr I have a doubt to separate the string -> route=A-C;140; and take only the 140

Show 8 more comments

3 answers

1

What’s the matter?

The problem is that the field public List<Node> conectados; is not being initialized next to the object Node.

Your program does all route calculation but at the time of passing the results it finds a null instead of the list conectados.

'Cause this is happening?

Although you have three constructors for class Node only two make the field initialization public List<Node> conectados; and just the only constructor you use in the code is the constructor that doesn’t initialize the field conectados.

Solution:

There are two solutions to your problem:

1 Within the class Node in the constructor whose signature is public Node(char data) make the following change:

        public Node(char data){
            this.data = data;

            //Adicione está linha para corrigir o problema.
            this.conectados = new List<Node>();
        }

2 Another solution would be to change, within the function Main(), the constructor used in your program which would look like this:

      for (int i = 0; i < text.Length; i++)
           {
                if (text[i].Contains("city"))
                {
                    // Essa era a linha antiga:
                    // listanos.Add(new Node(text[i][5]));
                    // que substitui por essa:
                    listanos.Add(new Node(text[i][5], new List<Node>()));
                }
            }
  • 1

    Thank you very much!!! makes perfect sense !

  • When you want to mark a question as solved choose an answer that you think is correct and the left side of it below the score has a symbol( ). Click on it which indicates that the issue has been resolved. Read What should I do if someone answers my question?

1

It is not a direct answer to the question, but with Ingles you can simplify your code:

static void Main(string[] args)
{
    String[] text = System.IO.File.ReadAllLines(@"C:\Users\Pedro Pacheco\Desktop\Mapa.txt");

    var result = text.Where(x => x.Contains("route"))
        .GroupBy(y => y[6])
        .Select(z => new Node(z.Key, z.Select(nf => new Node(nf[8])).ToList()))
        .ToList();

    // Adiciona existentes em "city" que não existem em "route" (neste caso 'H')
    result.AddRange(text.Where(x => x.Contains("city") && !result.Any(y => y.data == x[5])).Select(x => new Node(x[5])));

    // Ordena pelos nodes pai
    result = result.OrderBy(x => x.data).ToList();

    Console.ReadKey();
}

public class Node
{
    public List<Node> conectados;

    public char data;

    public Node(char data, List<Node> conectados)
    {
        this.conectados = conectados;
        this.data = data;
    }

    public Node(char data)
    {
        this.data = data;
    }
}
  • 1

    +1. I liked this code was very clear.

-2

city=A(100,80);
city=B(160,70);
city=C(110,50);
city=D(140,120);
city=F(155,40);
city=G(210,60);
city=H(190,10);
city=I(170,110);
route=A-C;140;
route=A-D;155;
route=C-F;125;
route=D-B;115;
route=D-I;152;
route=B-F;119;
route=B-G;136;
route=G-F;133;
route=F-H;163;
route=I-H;197;
  • you’re not the urge to public List<Node> conectados within the Node class... would be public List<Node> conectados = new List<Node>(); but edit the question and put an example of whatever contains the lists

  • it is quite simple what I want, see that in the class Node has public char and a public List<Node> previously I register in a list all Nodes with only the char assigned, and later I would like to access these Nodes without the child nodes and assigning, as the Map says

Browser other questions tagged

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