2013-04-02 3 views
-1

Я пытаюсь выполнить Breath First Search на графике, который я создаю из списка смежности из текстового файла «Input.txt». Я получаю исключение NullPointerException в строке 162, где указано «root.visited = true; " Я не могу понять, почему это так. Вот какой код у меня есть.NullPointerException Java BFS

 import java.io.BufferedReader; 
    import java.io.FileNotFoundException; 
    import java.io.FileReader; 
    import java.io.IOException; 
    import java.util.ArrayList; 
    import java.util.Iterator; 
    import java.util.LinkedList; 
    import java.util.Queue; 
    import java.util.Stack; 

    public class BFS { 
    public static void main(String[] args) { 
     { 
      Graph g = new Graph(); 
      // Making Adjacency Matrix 
      ArrayList<ArrayList<Integer>> adjacency = new ArrayList<ArrayList<Integer>>(); 
      adjacency.add(new ArrayList<Integer>()); 

      String input = "input.txt"; 
      Graph MyGraph = new Graph(); 
      boolean root = true; 
      Vertex n = null; 
      int j = 0; 
      try { 
       // Reading in the Input File to the Adjacency Matrix 
       BufferedReader reader = new BufferedReader(
         new FileReader(input)); 
       String line = reader.readLine(); 

       while (line != null) { 
        // Getting numbers from each line 
        String[] numbers = line.split(","); 
        int[] values = new int[numbers.length]; 
        for (int i = 0; i < numbers.length; i++) 
         values[i] += Integer.parseInt(numbers[i]); 

        // Adding values to Matrix 
        for (int i = 0; i < values.length; i++) { 
         adjacency.get(j).add(values[i]); 
         System.out.print(" " + adjacency.get(j).get(i)); // output 
                      // of 
                      // matrix 
        } 
        System.out.print("\n"); 

        // Progressing through file 
        adjacency.add(new ArrayList<Integer>()); 
        line = reader.readLine(); 
        j++; 
       } 

       // read each line 
       for (int currRow = 0; (line = reader.readLine()) != null; currRow++) { 
        String[] row = line.split(","); 

        // insert vertices 
        if (currRow == 0) { 

         for (int i = 0; i < row.length; i++) { 
          g.addVertex(n); 
          if (root = true) { 

          } 
         } 
        } 

        // create the edges specified in this row 
        for (int i = 0; i < row.length; i++) { 

         // edge exists between indices 'currRow' and col 'i'. 
         if (Integer.parseInt(row[i]) == 1) { 
          g.connectVertex(currRow, i); 
         } 
        } 
       } 
       reader.close(); 
      } catch (FileNotFoundException e) { 
       System.out.println(e); 
      } catch (IOException e) { 
       System.out.println(e); 
      } 

      /* DFS Algorithm */ 

      // schtuff (use stack? use index of node for unique number?) 

      // System.out.print("Visited nodes (in order): "); 

     } 

     // catch exceptions & errors 
     Graph MyGraph = new Graph(); 
     MyGraph.dfs(); 
    } 

    public static class Graph { 
     public Vertex root; 
     public ArrayList<Vertex> vertices = new ArrayList<Vertex>(); 
     public ArrayList<Vertex> dfsArrList = new ArrayList<Vertex>(); 
     public int[][] adjMatrix; 
     int size; 

     public void setRootVertex(Vertex n) { 
      this.root = n; 
     } 

     public Vertex getRootVertex() { 
      return this.root; 
     } 

     public void addVertex(Vertex n) { 
      vertices.add(n); 
     } 

     public void removeVertex(int loc) { 
      vertices.remove(loc); 
     } 

     public void connectVertex(int vertexStart, int vertexEnd) { 
      if (adjMatrix == null) { 
       size = vertices.size(); 
       adjMatrix = new int[size][size]; 
      } 

      int startIndex = vertices.indexOf(vertexStart) + 1; 
      int endIndex = vertices.indexOf(vertexEnd) + 1; 
      adjMatrix[startIndex][endIndex] = 1; 
      adjMatrix[endIndex][startIndex] = 1; 
     } 

     public void removeEdge(Vertex v1, Vertex v2) { 

      int startIndex = vertices.indexOf(v1); 
      int endIndex = vertices.indexOf(v2); 
      adjMatrix[startIndex][endIndex] = 1; 
      adjMatrix[endIndex][startIndex] = 1; 
     } 

     public int countVertices() { 
      int ver = vertices.size(); 
      return ver; 
     } 

     private Vertex getUnvisitedChildNode(Vertex n) { 

      int index = vertices.indexOf(n); 
      int j = 0; 
      while (j < size) { 
       if (adjMatrix[index][j] == 1 
         && vertices.get(j).visited == false) { 
        return vertices.get(j); 
       } 
       j++; 
      } 
      return null; 
     } 

     public Iterator<Vertex> dfs() { 

      Stack<Vertex> s = new Stack<Vertex>(); 
      s.push(this.root); 
      root.visited = true; 
      printVertex(root); 
      while (!s.isEmpty()) { 
       Vertex n = s.peek(); 
       Vertex child = getUnvisitedChildNode(n); 
       if (child != null) { 
        child.visited = true; 
        dfsArrList.add(child); 
        s.push(child); 
       } else { 
        s.pop(); 
       } 
      } 
      clearVertices(); 
      return dfsArrList.iterator(); 
     } 

     private void clearVertices() { 
      int i = 0; 
      while (i < size) { 
       Vertex n = vertices.get(i); 
       n.visited = false; 
       i++; 
      } 
     } 

     private void printVertex(Vertex n) { 
      System.out.print(n.vertexName + " "); 
     } 
    } 

    public class Vertex { 

     public char vertexName; 
     public boolean visited = false; 

     public Vertex(char l) { 
      this.vertexName = l; 
     } 

    } 

} 
+0

А где трассировка стека исключений? Предоставьте только соответствующий код –

+0

Первое, что облегчает отслеживание изменений ваших переменных: сделать их частными. Зачем вам беспокоиться о сеттерах и геттерах, пока почти все ваши переменные являются общедоступными? Далее: вы никогда не вызываете setRootVertex ... –

+0

Ваш 'root' имеет значение NULL. – Shark

ответ

1

Посмотрите на этот код (который немного причудливо после рамно части main):

Graph MyGraph = new Graph(); 
MyGraph.dfs(); 

Метод dfs начинается с:

Stack<Vertex> s = new Stack<Vertex>(); 
s.push(this.root); 
root.visited = true; 

Что вы ожидаете MyGraph.root в будь здесь? Как это может быть ничего, кроме нуля? (.. Обратите внимание, что у вас есть два MyGraph переменные объявлены в main Первый не используется ни для чего, по какой-то причине)

Я настоятельно рекомендую вам перестроить этот значительно код:

  • реорганизовать main способ быть меньше
  • Избегайте введения новой области только ради этого - тот факт, что ваш основной метод является эффективным:

    public static void main(String[] args) { 
        { 
         // Code 
        } 
    } 
    

    очень странно.

  • Избегай вложенные классы, когда вы на самом деле не нуждаются в них: использовать отдельные файлы
  • Избегайте общие переменные
  • Сделайте ваши данные неизменны, где вы можете. Вам действительно нужно изменить корень вершины после строительства? Не могли бы вы передать его конструктору? Такие вещи делают код более понятным.
+0

Мне нравится ваша скорость в ответе на детали. –

+0

На данный момент я просто хочу установить вершин «n» на что-то другое, кроме «Null», я хотел бы установить его в первую вершину в списке смежности здесь http://pastebin.com/ 5a0vbEjy – Cfox7

+0

Еще один прекрасный ответ действительно Джон. – Shark

0

Vertex root не инициализируется так root.visited становится null.visited во время выполнения, которые вызывают NullPointerException.

Vertex root Ожидается, что значение будет установлено на setRootVertex.

0

Когда вы вызываете
MyGraph.dfs();
public static class Graph { public Vertex root;

Ваш корень не инициализирован.