试图在多个空格上拆分字符串

时间:2016-05-04 22:35:34

标签: java

public Graph(String graphFile) throws IOException {
    int u, v;
    int e, wgt;
    Node t;

    Scanner sc = new Scanner(new File(graphFile));
    String graphType = sc.next();
    boolean undirected = true;
    if (graphType.equals("directed")) {
        undirected = false;
    }

    FileReader fr = new FileReader(graphFile);
    BufferedReader reader = new BufferedReader(fr);

    String splits = " +";  // multiple whitespace as delimiter
    String line = reader.readLine();
    String[] parts = line.split(splits);
    System.out.println("Parts[] = " + parts[0] + " " + parts[1]); // THE ERROR IS THIS LINE

    V = Integer.parseInt(parts[0]);
    E = Integer.parseInt(parts[1]);
}


public class PrimLists {
    public static void main(String[] args) throws IOException {
        int s = 2;
        Scanner sc = new Scanner(System.in);
        System.out.println("enter graph input file name:");
        String file = sc.nextLine();
        Graph g = new Graph(file); // THE ERROR IS THIS LINE
        //Graph g = new Graph(fname);

        g.display();
    }
}

我一直收到以下错误

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at Graph.<init>(PrimLists.java:170)
    at PrimLists.main(PrimLists.java:315)

我正在阅读文本文件图表:

9
A
B
C
D
E
F
G
H
I
A B 1
B C 2
C E 7
E G 1
G H 8
F H 3
F D 4
D E 5
I F 9
I A 3
A D 1

有谁知道为什么这不起作用,可以帮助我?

1 个答案:

答案 0 :(得分:0)

此行不正确

String splits = " +";  // multiple whitespace as delimiter

你可能意味着正确表达

String splits = "\\s+";  // multiple whitespace as delimiter

问题是您的字符串不包含文字" +",因此它们没有被拆分。

另请注意,任何没有空格的行(例如您显示的前10行)都会在parts[1]处出错,因此您应先检查parts.length