我想從java中的文本文件讀取一行。我得到一個java.lang.ArrayIndexOutOfBoundsException: 1
例外。Java .split()由字符串中的空格組成
這裏是我的代碼:
try {
Scanner kb = new Scanner(new FileReader(fileName));
String line = "";
int count = 0;
while (kb.hasNext()) {
line = kb.next();
String[] temp = line.split("#");
System.out.println(temp[1]);
Wedding tempWed = new Wedding(temp[0], temp[1], temp[2], temp[3], Integer.parseInt(temp[4]));
test[count] = tempWed;
count++;
}
} catch (FileNotFoundException ex) {
}
這是文本文件的行:
Chiquita Sanford#Magee Sosa#2016-11-05#Garden#84
我需要用 「#」 分裂,而這部分工作。 當我嘗試訪問位置1處的元素時,Java拋出異常。 我認爲這是因爲名字和姓氏之間存在空格,因爲當我顯示「Chiquita」而不是「Chiquita Sanford」時。
當第一個數組索引中有多個單詞時,Java是否對分割有一些限制。
將'kb.next()'更改爲'kb.nextLine()',並將'kb.hasNext()'更改爲'kb.hasNextLine()'。 – Andreas
更好的是,不要使用'掃描儀',因爲它很慢。改爲使用'BufferedReader'及其''readLine()'方法。 – Andreas