英文:
Exception read data from file while split character "|"
问题
Your translated code:
public void loadDataFromFile(ArrayList<Book> list, String fileName) {
File f = new File(fileName);
try {
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
String perLine = sc.nextLine(); //get data per line
String txt[] = perLine.split(" ");
list.add(new Book(txt[0], txt[1], Integer.parseInt(txt[2]), Double.parseDouble(txt[3])));
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
Please note that I've changed the split delimiter from "|"
to " "
, as mentioned in your explanation, for it to work correctly.
英文:
public void loadDataFromFile(ArrayList<Book> list, String fileName) {
File f = new File(fileName);
try {
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
String perLine = sc.nextLine(); //get date per line
String txt[] = perLine.split("|");
list.add(new Book(txt[0], txt[1], Integer.parseInt(txt[2]), Double.parseDouble(txt[3])));
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
My function read data from file and add data to arraylist. But when I run this function, it have bug like this picture
<br>My file is book.txt
and data of this file is
A2|Hoa|22|50.3
. If i try split at character "|"
, it will have bug like this picture. But if i change data of file to A2 Hoa 22 50.3
and split at " "
it working.
答案1
得分: 2
在Java中,String
的split()
方法使用正则表达式作为参数工作,因为|
在正则表达式中是特殊字符,所以你需要使用\\|
来转义它,如下所示:perLine.split("\\|");
英文:
In java String
split()
method work's with regex as argument since '|' is special character in regex you need to escape it with \\ as folowing perLine.split("\\|");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论