Первый поиск по глубине и индекс строки вне диапазона: -3 - PullRequest
0 голосов
/ 29 декабря 2018

Используя GraphRead-класс, я не писал сам, я должен выполнить алгоритм поиска в глубину для редактирования графиков из текстовых файлов.

Вот как выглядит класс:

public class GraphRead {

    public static Graph<Vert,Edge<Vert>> FileToGraph(String dat, boolean directed, boolean standardIds, boolean weighted) {
        FileInputStream fis = null;
        Graph<Vert,Edge<Vert>> G = null;
        try {
          fis = new FileInputStream(dat);
        }
        catch ( Exception e) {
            System.out.println(dat + " couldn't be opened");
            System.out.println(e.getMessage());
        }
        try {
              InputStreamReader isr   = new InputStreamReader(fis);
              BufferedReader    br = new BufferedReader   (isr);

              // read number of vertices
              String aRow;
              aRow = br.readLine();
              int n = new Integer(aRow);

              // read number of edges
              aRow = br.readLine();
              int m = new Integer(aRow);

              // construct graph
              G = new Graph<Vert,Edge<Vert>>(n, directed);

              if (!standardIds) { // vertices have arbitrary ids and get a name
                  // read vertices (1. substring: id, 2. substring: name)
                  for (int i = 1; i <= n; i++) {
                      aRow = br.readLine();
                      int sepIndex1 = aRow.indexOf(' ');
                      String vId = aRow.substring(0, sepIndex1);
                      String vStr = aRow.substring(sepIndex1+ 1, aRow.length());
                      int id = new Integer(vId);
                      Vert v = new Vert(id,vStr);
                      G.addVertex(v);
                  }
              }
              else {
                // add vertices with standard ids (0 .. n-1)
                for (int i = 0; i < n; i++) {
                    G.addVertex(new Vert(i));
                }
              }
              // read edges with weight
              if (weighted) {
                  for (int i = 1; i <= m; i++) {
                      aRow = br.readLine();
                      int sepIndex1 = aRow.indexOf(' ');
                      int sepIndex2 = aRow.indexOf(' ', sepIndex1+1);
                      String vStr = aRow.substring(0, sepIndex1);
                      String uStr = aRow.substring(sepIndex1+ 1, sepIndex2);
                      String wStr = aRow.substring(sepIndex2+ 1, aRow.length());
                      int vId = new Integer(vStr);
                      int uId = new Integer(uStr);
                      int w = new Integer(wStr);

                      Vert v = G.getVertex(vId);
                      Vert u = G.getVertex(uId);

                     G.addEdge(new Edge<Vert>(v,u,w));
                  }
              }
              else { // read edges without weight; 
                  for (int i = 1; i <= m; i++) {
                      aRow = br.readLine();
                      int sepIndex1 = aRow.indexOf(' ');
                      String vStr = aRow.substring(0, sepIndex1);
                      String uStr = aRow.substring(sepIndex1+ 1, aRow.length());
                      int vId = new Integer(vStr);
                      int uId = new Integer(uStr);

                      Vert v = G.getVertex(vId);
                      Vert u = G.getVertex(uId);

                     G.addEdge(new Edge<Vert>(v,u));
                  }  
              }
            fis.close();
          }
          catch (Exception e) {
                System.out.println("Reading was not successful");
                System.out.println(e.getMessage());
          } 

        return G;   

    }
}

Я всегда получаю исключение «Строковый индекс вне диапазона 3».И я понятия не имею, почему.

Файл имеет следующий формат: 1. строка: количество вершин (n) 2. строка: количество ребер (m) Идентификаторы вершин и названия вершин разделяются пробелом.Последующие m строк: начальный и конечный вершины ребра и вес ребра (только если weighted = true) разделены пробелами.
Параметр направлен на true, если граф направлен.В случае, если оно направлено: каждое ребро e = (a, b) в «dat» добавляется только в список смежности переменной a.Если он не направлен: каждое ребро e = (a, b) добавляется в список смежности переменной a и в список смежности переменной b.Параметр "standardIds" имеет значение true, если вершины имеют идентификаторы от 0 до n-1 и не имеют имен.Параметр weighted имеет значение true, если ребра взвешены.

Содержимое Graph-txt выглядит следующим образом:

9
11
0 1
0 4
1 2
2 5
5 3
3 2
3 0
3 4
6 3
7 6
8 7
9

Есть идеи, как мне это решить?Спасибо!

1 Ответ

0 голосов
/ 30 декабря 2018

Ошибка возникает в этой строке

String uStr = aRow.substring(sepIndex1+ 1, sepIndex2);

, и причина в том, что в вашем файле есть только (макс.) 2 числа и, таким образом, только один пробел, следующий для sepIndex2-1, поскольку sepIndex1 равно 1

int sepIndex2 = aRow.indexOf(' ', sepIndex1+1);

Для ясности, это то, что я использовал при тестировании.

Окончательный вариант входного файла

9
2
0 1
0 4
1 2
2 5
5 3
3 2
3 0
3 4
6 3
7 6
8 7

И моя версия кода, где я удалиллюбые ссылки на неизвестные классы, такие как Graph и т. д., а также некоторые другие правки.Это было сделано, так как меня интересовала только логика чтения файла

public static void main(String[] args) {
    GraphRead.FileToGraph("~/temp/graf.txt", true, false, false);
}

public static void FileToGraph(String dat, boolean directed, boolean standardIds, boolean weighted) {
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(dat);
    } catch (Exception e) {
        System.out.println(dat + " couldn't be opened");
        System.out.println(e.getMessage());
    }
    try {
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);

        // read number of vertices
        String aRow;
        aRow = br.readLine();
        int n = new Integer(aRow);

        // read number of edges
        aRow = br.readLine();
        int m = new Integer(aRow);

        if (!standardIds) { // vertices have arbitrary ids and get a name
            // read vertices (1. substring: id, 2. substring: name)
            System.out.println("!standardIds");
            for (int i = 1; i <= n; i++) {
                aRow = br.readLine();
                int sepIndex1 = aRow.indexOf(' ');
                String vId = aRow.substring(0, sepIndex1);
                String vStr = aRow.substring(sepIndex1 + 1, aRow.length());
                int id = new Integer(vId);
                System.out.println(vId + ":" + vStr);
            }
        }

        // read edges with weight
        if (weighted) {
            System.out.println("weighted");
            for (int i = 1; i <= m; i++) {
                aRow = br.readLine();
                int sepIndex1 = aRow.indexOf(' ');
                int sepIndex2 = aRow.indexOf(' ', sepIndex1 + 1);
                String vStr = aRow.substring(0, sepIndex1);
                String uStr = aRow.substring(sepIndex1 + 1, sepIndex2);
                String wStr = aRow.substring(sepIndex2 + 1, aRow.length());
                System.out.println(uStr + ":" + wStr);
            }
        } else { // read edges without weight;
            System.out.println("!weighted");
            for (int i = 1; i <= m; i++) {
                aRow = br.readLine();
                int sepIndex1 = aRow.indexOf(' ');
                String vStr = aRow.substring(0, sepIndex1);
                String uStr = aRow.substring(sepIndex1 + 1, aRow.length());
                System.out.println(vStr + ":" + uStr);
            }
        }
        fis.close();
    } catch (Exception e) {
        System.out.println("Reading was not successful");
        System.out.println(e.getMessage());
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...