I have a text file with this information:
dog
sheep
cat
horse
cat
tiger
cat
cat
tiger
In another Q&A, I asked people how to count all the animal occurences, which I did with this method:
void countAnimals(){
Map m1 = new HashMap();
try (BufferedReader br = new BufferedReader(new FileReader("Animals.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
String[] words = line.split(" ");//those are your words
for (int i = 0; i < words.length; i++) {
if (m1.get(words[i]) == null) {
m1.put(words[i], 1);
} else {
int newValue = Integer.valueOf(String.valueOf(m1.get(words[i])));
newValue++;
m1.put(words[i], newValue);
}
}
sb.append(System.lineSeparator());
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Map<String, String> sorted = new TreeMap<String, String>(m1);
for (Object key : sorted.keySet()) {
System.out.println(key + "\t Votes: " + m1.get(key));
}
}
This is what the console prints out:
cat Votes: 4
dog Votes: 1
horse Votes: 1
sheep Votes: 1
tiger Votes: 2
Can someone help me on how to put the information, now printed to the console, into a two dimensional array, which I am going to put into a JTable
?
Update: Here's what I added to my countAnimals
method:
Map<String, String> sorted = new TreeMap<String, String>(m1);
for (Object key : sorted.keySet()) {
System.out.println(key + "\t Votes: " + m1.get(key));
}
AnimalSummaryModel SOCLOSE = new AnimalSummaryModel(sorted);
SOCLOSE.run();
And the AnimalSummaryModel
class you have provided looks like this:
class AnimalSummaryModel extends AbstractTableModel {
private final String[] keys;
private Map<String, String> data;
public AnimalSummaryModel(Map<String, String> data) {
this.data = data;
keys = data.keySet().toArray(new String[data.size()]);
}
public int getColumnCount() {
return 2;
}
public int getRowCount() {
return data.size();
}
public Object getValueAt(int row, int col) {
if (col == 0) {
return keys[row];
} else {
return data.get(keys[row]);
}
}
private void display() {
JFrame f = new JFrame("EnvTableTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(f, this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public void run() {
display();
}
}
I'm still getting nowhere.