[英]Not able to assign a text for a string in array using split method
我對讀取 function 的文件中的拆分 function 有疑問。 這是我的代碼。 我嘗試使用 split 將這些文本放入數組中。 但問題是我有這個錯誤。 java.lang.NumberFormatException:對於輸入字符串:“Sug”在 java.base/java.lang.NumberFormatException.forInputString
public static SLL<train> readFile() {
SLL<train> list = new SLL();
try {
FileReader fr = new FileReader("Train.dat");
BufferedReader br = new BufferedReader(fr);
String line = "";
while (true) {
line = br.readLine();
if (line == null) {
break;
}
String[] text = line.split(" | ");
String tcode = text[0];
String train_name = text[1];
int seat = Integer.parseInt(text[2]);
int booked = Integer.parseInt(text[3]);
double depart_time = Double.parseDouble(text[4]);
String depart_place = text[5];
train t = new train(tcode, train_name, seat, booked, depart_time, depart_place);
list.addLast(t);
}
br.close();
fr.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
“SUG”應該添加到火車名稱中,因為我將train_name聲明為字符串。我認為只有在聲明錯誤的數據類型時才會出現此錯誤,“12”應該添加到座位中,“3”應該添加到預訂中,所以上。 你們能向我解釋一下“SUG”發生了什么嗎? 非常感謝:(
請注意, String.split(regex)
使用正則表達式來查找拆分位置,即它在正則表達式產生的任何匹配之前和之后拆分。
此外,在正則表達式中 pipe ( |
) 具有特殊含義“或”,因此您的代碼現在讀作“在空格或空格上分割”。 由於這僅在空格上拆分,拆分"B03 | Sug | 12..."
將導致數組["B03","|","Sug","|","12",...]
並因此text[2]
產生"Sug"
。
相反,您需要使用line.split(" \\| ")
或line.split(Pattern.quote(" | "))
以使其“在空間序列上拆分,pipe, 空間”。 這將導致["B03","Sug","12",...]
。
但是,您可能還需要用 try-catch 塊包圍Integer.parseInt()
等,或者對字符串進行一些初步檢查,因為您可能會遇到格式錯誤的文件。
除了@Thomas 所說的,使用Scanner
會容易得多
sc.useDelimiter("\\s*\\|\\s*");
while (sc.hasNext()) {
Train t = new Train(sc.next(), sc.next(), sc.nextInt(), sc.nextInt(), sc.nextDouble(), sc.next());
}
命名在 Java 中對於可讀性和維護很重要 注意 class 名稱在 Java 中以大寫開頭。 沒有下划線的位置,除了以常量的名義作為大寫字母的分隔符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.