所以我有一个动物园数据库,游客可以在那里看到不同种类的动物。每个参观者都有自己的日志,记录他看到了什么动物以及什么时候看到的。我正在尝试创建一个访问者看到的所有动物的列表,并分离出访问者的唯一id。如果参观者在不同的日子看到同一种动物,则将该动物被看到的次数映射到动物名称。我只需要列表中动物的名称,以及用于其他处理目的的客户端id。日期并不重要。示例日志如下所示。
ClientId: 1001
Zebra 10/1
Cheetah 10/2
Tiger 10/2
Lion 10/3
Zebra 10/4这是我的日志类:
public class Log {
private int clientId;
private int animalCount = 1;
private Map<String, Integer> animalList = new HashMap<String, Integer>();
public void addFromFile(String fileName) {
File file = new File(fileName);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
}
while (sc.hasNextLine()) {
sc = new Scanner(sc.nextLine());
String s = sc.next();
//Don't add the dates. Only the Strings
if (!isNumeric(s)) {
if (animalList.containsKey(s)) {
animalList.put(s, animalList.get(s) + 1);
} else {
animalList.put(s, animalCount);
}
}
}
}
public Map<String, Integer> getList() {
return animalList;
}
public int getClientId() {
return this.clientId;
}
public int itemCount() {
return this.itemCount;
}
public boolean isNumeric(String str) {
return Character.isDigit(str.charAt(0));
}
}日志将始终按该顺序显示。我在先处理客户Id行,然后再处理动物名称时遇到了问题。
使用上述示例日志的以下内容的输出为:
Log log = new Log();
log.addFromFile("DataSetOne1.txt");
System.out.println(log.getList());
//Output: {ClientId:=1}我的代码在第一行就卡住了。我希望能够处理第一行,并首先处理它,因为它包含我唯一关心的整数值。我只是对如何处理这个问题感到困惑。
发布于 2015-11-22 05:55:05
如果每个条目都在单独的行上,则循环遍历字符,直到在每行上找到digits (数字)或:字符,并将字符存储在二维数组中或列表中的数组中。
如果在一行上找到的字符是:,丢弃之前获取的该行的字符,并记录这些字符直到行尾,这将通过一个String.trim()获得您的访问者ID。
否则,如果找到一个数字,就停止记录字符,并跳出该行的循环,同样,在.trim()之后,您应该知道动物的名称。
PS: RegEx或模式匹配器更难理解(就像你在OP的评论中指出的那样),但会让这变得容易得多。如果你想使用字符串或文件解析,你真的应该,真的,,,,,来学习这些东西。
发布于 2015-11-23 02:58:30
最终弄明白了一些事情。这不是最优雅的解决方案,但它确实起到了作用。
public void addFromFile(String fileName) {
File file = new File(fileName);
Scanner sc = null;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc.hasNextLine()) {
Scanner sc2 = new Scanner(sc.nextLine());
while (sc2.hasNext()) {
String s = sc2.next();
if (!isNumeric(s)) {
// Retrieve the client ID and assign it to the instance
// variable
if (s.equals("ClientId:")) {
clientId = Integer.parseInt(sc2.next());
}
if (animalList.containsKey(s)) {
animalList.put(s, animalList.get(s) + 1);
} else {
animalList.put(s, animalCount);
}
}
}
}
// Delete the ClientId entry
animalList.remove("ClientId:");
}https://stackoverflow.com/questions/33848819
复制相似问题