rendered paste bodyimport java.io.*;
import java.util.*;
public class PetCount {
public static void main( String[] args ){
try {
HashMap<String, Integer> pets = new HashMap<String, Integer>();
String line;
boolean onPet = false;
File fileName = new File("pets.txt");
BufferedReader fileIn = new BufferedReader(new FileReader(fileName));
while (( line = fileIn.readLine()) != null){
if( !line.trim().equals("")) {
if( line.equals("<pet>") )
onPet = true;
else if( line.equals("</pet>") )
onPet = false;
else if( onPet ){
if( line.contains("<type>")){
String type = line.replaceAll("<type>", "");
type = type.replaceAll("</type>", "").trim();
if( pets.containsKey( type ) ) {
pets.put(type, (Integer)(pets.get(type)) + 1);
}else{
pets.put(type, 1);
}
}
}
}
}
int sum = 0;
Set<String> keys = pets.keySet();
Iterator<String> It = keys.iterator();
while (It.hasNext()) {
String currKey = (String)(It.next());
System.out.println("Pets of type " + currKey + ": " + pets.get(currKey));
sum = sum + (Integer)pets.get(currKey);
}
System.out.println( "Total pets: " + sum );
}
catch (FileNotFoundException e) {
System.err.println( "File cannot be found." );
}
catch (IOException e) {
System.err.println( "File cannot be read." );
}
}
}