[英]Trying to split a string on multiple spaces
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();
}
}
I keep getting the following error 我不断收到以下错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Graph.<init>(PrimLists.java:170)
at PrimLists.main(PrimLists.java:315)
I am reading in a text file graph which is this: 我正在阅读一个文本文件图,这是:
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
Does anyone know why this is not working and could help me out?? 有谁知道为什么这不起作用,可以帮助我吗?
This line is not correct 这行是不正确的
String splits = " +"; // multiple whitespace as delimiter
You probably meant a proper regular expression of 您可能是说正确的正则表达式
String splits = "\\s+"; // multiple whitespace as delimiter
The problem is that your strings do not contain a literal " +"
, and so they were not being split. 问题在于您的字符串不包含文字
" +"
,因此它们没有被拆分。
Also note that any line that does not have any spaces on it, such as about the first 10 you've shown will error at parts[1]
, so you should check parts.length
first. 还要注意,任何没有空格的行(例如您显示的前10个行)都会在
parts[1]
处出错,因此应首先检查parts.length
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.