索引736超出长度500的范围

时间:2019-03-13 15:13:25

标签: java exception

我正在尝试读取一些csv文件并构建图形,但始终收到此消息:

Exception in thread "main" 
java.lang.ArrayIndexOutOfBoundsException: 
Index 736 out of bounds for length 500
at CitiesClass.main(CitiesClass.java:35)

这显然是这一行

[Integer.parseInt(results[1])]=1.0;

但是我到底在做什么错?

完整代码:

import java.io.*;
import java.util.Scanner;
import java.util.*;

class CitiesClass {

 static int N = 500;
 static double [][] edges = new double[N][N];
 static TreeMap <Integer,String> cityNames = new TreeMap
    <Integer,String>();
 static ArrayList<String> convert(ArrayList<Integer> m) {
    ArrayList<String> z = new ArrayList<String>();
    for (Integer i:m) z.add(cityNames.get(i));
    return z;
   }

 static HashSet<ArrayList<String>> convert
  (HashSet<ArrayList<Integer>> paths) {
    HashSet <ArrayList <String>> k = new HashSet <ArrayList<String>>();
    for (ArrayList <Integer> p:paths) k.add(convert(p));
    return k;
    }

public static void main(String[] args) throws Exception {
  for(int i=0;i<N;i++)
  for(int j=0;j<N;j++)
  edges[i][j]=0.0;
  Scanner s = new Scanner(new FileReader("randomGraph.csv"));
  String z = s.nextLine();
  while (s.hasNext()) {
    z =s.nextLine();
    String[] results = z.split(",");
    edges[Integer.parseInt(results[0])]
    [Integer.parseInt(results[1])]=1.0;
    edges[Integer.parseInt(results[1])]
    [Integer.parseInt(results[0])]=1.0;
  }

  s = new Scanner(new FileReader("cities.csv"));
  z =s.nextLine();
  while (s.hasNext()) {
    z =s.nextLine();
    String[] results = z.split(",");
    cityNames.put(Integer.parseInt(results[0]), results[1]);
  }

  graph G = new graph(edges);
  int st = Integer.parseInt(args[0]);
  int fin = Integer.parseInt(args[1]);
  System.out.println("Shortest path from " + cityNames.get(st)
      + " to " + cityNames.get(fin) + " is" + 
      convert(G.shortestPaths(st,fin)));
  }
}

1 个答案:

答案 0 :(得分:0)

  

但是我到底在做什么错?

您假设使用0 <= Integer.parseInt(results[1]) < 500。显然,您正在读取的图形至少包含736个节点(如果图形的索引基于零,则为737)。

我可能想看看randomGraph的第一行(您丢弃的那一行)是否包含图形的大小。

String z = s.nextLine();

尝试解析:

int graphSize = Integer.parseInt(z);

,然后根据此分配矩阵:

edges = new double[graphSize][graphSize]