想简化下面的代码,用switch语句代替if语句来提高效率,但是不知道switch()括号中的判别式怎么写,请各位帮忙,谢谢!
public void Text_identify(File f) {
HashMap GlobalMode = new HashMap();
String[] input = readAllFile(f).replaceAll(" ", ";").split(";");
for (int i = 0; i < input.length; i++) {
String re = input[i].replace(",", " ").trim();
if (re.startsWith("Book Title")) {
booktitle = input[i].substring(input[i].indexOf("-") + 2);
GlobalMode.put("booktitle", booktitle);
contiue;
}
if (re.startsWith("Chapter Title")) {
title = input[i].substring(input[i].indexOf("-") + 2);
GlobalMode.put("title", title);
contiue;
}
// 多个作者识别
if (re.startsWith("Author")) {
StringBuffer au = new StringBuffer();
author = au.append(input[i].substring(input[i].indexOf("-") + 2)).toString();
String authorNames = GlobalMode.get("author");
authorNames = (authorNames == null) ? author : (authorNames + "," + author);
GlobalMode.put("author", authorNames);
contiue;
}
if (re.startsWith("Copyright")) {
year = input[i].substring(input[i].indexOf("-") + 2);
GlobalMode.put("year", year);
contiue;
}
if (re.startsWith("isbn")) {
isbn = input[i].substring(input[i].indexOf("-") + 2);
GlobalMode.put("isbn", isbn);
contiue;
}
}
补充:目的是处理这样的文本:
Book Series -
Book Title - Graph Drawing
Chapter Title - VGJ: Visualizing Graphs Through Java
First Page - 454
Last Page - 455
Copyright - 1998
Author - Carolyn McCreary
Author - Larry Barowski
识别BookTitle = 对应值;author=对应值;..
[b]问题补充:[/b]
不能用switch,那有没有其他简单高效的方法来代替如此多重复的if-else呢?
[b]问题补充:[/b]
我试着用enum了,但是不知道怎么把字符串赋给enum,还有就是switch中的判别式不知道如何写,能否详细说一下呢?谢谢!
[b]问题补充:[/b]
1. 代码里变量booktitle, title, author, year, isbn是用来存放他们的对应值,在其他方法里也用到了
2. Java代码
String[] input = readAllFile(f).replaceAll(" ", ";").split(";"); 这里replace完再split确实没必要,我已经按你的方法修改了。
3. globalMode最后要返回给方法调用者,我最后想要的是:可以自己定义booktitle, title, author, year, isbn对应值的显示顺序。像参考文献那样的格式。