I'm writing a program that counts the occurrences of integers entered into an array, eg if you entered 1 1 1 1 2 1 3 5 2 3, the program would print out the distinct numbers followed by their occurrences, like this:
1 occurs 5 times, 2 occurs 2 times, 3 occurs 2 times, 5 occurs 1 time
And it's almost finished, aside from one problem I can't figure out:
import java.util.Scanner;
import java.util.Arrays;
public class CountOccurrences
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
final int MAX_NUM = 10;
final int MAX_VALUE = 100;
int [] numList;
int num;
int numCount;
int [] occurrences;
int count[];
String end;
numList = new int [MAX_NUM];
occurrences = new int [MAX_NUM];
count = new int [MAX_NUM];
do
{
System.out.print ("Enter 10 integers between 1 and 100: ");
for (num = 0; num < MAX_NUM; num++)
{
numList[num] = scan.nextInt();
}
Arrays.sort(numList);
count = occurrences (numList);
System.out.println();
for (num = 0; num < MAX_NUM; num++)
{
if (num == 0)
{
if (count[num] <= 1)
System.out.println (numList[num] + " occurs " + count[num] + " time");
if (count[num] > 1)
System.out.println (numList[num] + " occurs " + count[num] + " times");
}
if (num > 0 && numList[num] != numList[num - 1])
{
if (count[num] <= 1)
System.out.println (numList[num] + " occurs " + count[num] + " time");
if (count[num] > 1)
System.out.println (numList[num] + " occurs " + count[num] + " times");
}
}
System.out.print ("\nContinue? <y/n> ");
end = scan.next();
} while (!end.equalsIgnoreCase("n"));
}
public static int [] occurrences (int [] list)
{
final int MAX_VALUE = 100;
int num;
int [] countNum = new int [MAX_VALUE];
int [] counts = new int [MAX_VALUE];
for (num = 0; num < list.length; num++)
{
counts[num] = countNum[list[num]] += 1;
}
return counts;
}
}
The problem I'm having is that no matter what the current value for 'num' is, 'count' only prints out 1, and the problem isn't in the method that counts the occurrences, because when you enter numbers in the place of the variable, the value changes.
Is there any way that I can alter this so that it'll print out the occurrences properly, or should I try something else? And the simpler the solution, the better, as I haven't yet gone past single dimension arrays.
Thanks for the help!