I'm trying to use a Scanner to read in a text file with fraction Strings of the form "a/b", store them in an array, then print to the console each unique one along with its count. I can print each separate entry in the text file with an accurate count, but I can't figure out how to print the contents of the array without any duplicates.
I'm also trying to accomplish this entirely within main. Here's what I've got so far:
public static void main(String[] args) throws FileNotFoundException
{
ArrayList<String> fracs = new ArrayList<String>();
Scanner input = new Scanner(new File("input.txt"));
ArrayList<String> fracsDisplay = new ArrayList<String>();
while(input.hasNext())
fracs.add(input.next());
for(int i = 0; i < fracs.size(); i++)
{
int count = 0;
for(int j = 0; j < fracs.size(); j++)
{
if(fracs.get(i).equals(fracs.get(j)))
count++;
}
System.out.println(fracs.get(i) + ": " + count);
}
input.close();
}
fracs.contains(...)if the array contains already an element and if so just increment the counter or avoid adding the element again. ASetis preventing duplicate entries by default. And why don't you use aMapif you want to print the entry-name as well as its count? Lookup the count (=value) via the unique entry (=key)