[英]Java Reading Words from a file with apostrophies and hypens and counting them as 2 words
[英]java - Reading specific words from a file
因此,我有一个动物园数据库,游客可以在这里看到不同种类的动物。 每个访客都有自己的日志,记录了他看见了什么动物以及何时看见了。 我正在尝试创建访问者看到的所有动物的列表,并分离出访问者的唯一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}
我的代码一直停留在第一行。 我希望能够处理第一行并首先使其摆脱干扰,因为它包含了我所关心的唯一整数值。 我只是对如何解决这个问题感到困惑。
如果每个条目都位于单独的行上,则循环遍历chars直到找到digits
(数字)或:
chars,然后在每一行上将chars存储在2D数组或列表中的数组中。
如果在一行上找到的字符为:
,则丢弃该行先前获取的字符,并记录该字符直到该行的末尾,使用String.trim()
可以获取访问者的ID。
否则,如果找到数字,则停止记录字符,并退出该行的循环,并且再次在.trim()
,您应该具有动物的名称。
PS:RegEx或Pattern-Matcher,较难理解(正如您在OP的评论中指出的那样),但这样做会更容易。 如果您想使用字符串或文件解析,则应该真的, 真的 , 真的 , 真的要学习这些知识。
最终弄明白了。 这不是最优雅的解决方案,但可以解决问题。
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:");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.