JAVA. Please I need the same output! Counting animals in a zoo All similar anima
ID: 3589637 • Letter: J
Question
JAVA. Please I need the same output! Counting animals in a zoo All similar animals in a zoo share the same cage. For example, south china tiger and javan tiger are in the same cage, and we only want to know there are two tigers. Given an integer K, followed by K lines describing animals, count and output in alphabetical order the animals in the zoo. The input data file includes multiple cases. Each case contains a number K (0<=K<=500), followed by K lines of animals with at least one word on each line, and the last word describing the kind of animal. For example, Caspian tiger is a tiger (obviously). The input is terminated by a 0. Output: For each test case, count and output the number for each animal type in alphabetic order: animal type followed by : and the number of that type animal. Other requirements: class name: CountingAnimals.java Sample input Sample output 5 List 1: Bengal tiger bear : 2 Brown bear tiger : 3 Sun bear List 2: South China tiger penguin : 2 Bali tiger 2 King penguin Fiordland penguin 0
Explanation / Answer
import java.io.File;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class CountingAnimals {
public static void main(String[] args) {
Scanner scanner = null;
try {
scanner = new Scanner(new File("input.txt"));
int n;
int j = 1;
while (scanner.hasNext()) {
n = Integer.parseInt(scanner.nextLine());
if (n == 0)
break;
String[] string = new String[n];
for (int i = 0; i < string.length; i++) {
string[i] = scanner.nextLine();
}
Map<String, Integer> countAn = countAnimals(string);
System.out.println("List " + (j++) + " : " + countAn);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* @param string
* @return
*/
public static Map<String, Integer> countAnimals(String[] string) {
Map<String, Integer> countAn = new TreeMap<String, Integer>();
for (int i = 0; i < string.length; i++) {
int l = string[i].split(" ").length;
String strings = string[i].split(" ")[l - 1];
if (countAn.get(strings) != null) {
int count = countAn.get(strings);
countAn.put(strings, ++count);
} else {
countAn.put(strings, 1);
}
}
return countAn;
}
}
input.txt
5
Bengal tiger
Brown bear
Sun bear
South China tiger
Bali tiger
2
King penguin
Fiordland penguin
0
OUTPUT:
List 1 :
{bear=2, tiger=3}
List 2 :
{penguin=2}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.