
Jin N.
asked 01/21/21Help me with this please
Write a static void method that will take accept an int array as a parameter and will count the number of times the numbers, 0-9, appear in the array, which can just be print statements
2 Answers By Expert Tutors
class DigitStats
{
private int A[];
private long freqTable[];
DigitStats( int a[])
{
//deep copies
int N = a.length;
A = new int[N];
for (int iLoop=0; iLoop<N; iLoop++)
{
A[iLoop]=a[iLoop];
}
//clears the frequencies
freqTable = new long[10];
for (int iLoop=0; iLoop<10; iLoop++)
{
freqTable[iLoop]=0;
}
}
void Set( int a[])
{
//deep copies
int N = a.length;
A = new int[N];
for (int iLoop=0; iLoop<N; iLoop++)
{
A[iLoop]=a[iLoop];
}
//clears the frequencies
freqTable = new long[10];
for (int iLoop=0; iLoop<10; iLoop++)
{
freqTable[iLoop]=0;
}
}
protected void CalculateFrequencies()
{
for (int iLoop=0; iLoop<A.length; iLoop++)
{
String iNumbuff = (new Integer(A[iLoop])).toString();
System.out.println(iNumbuff);
int nStrLen = iNumbuff.length();
for (int jLoop=0; jLoop<nStrLen; jLoop++)
{
char chDigit = iNumbuff.charAt(jLoop);
if ((chDigit>='0') && (chDigit<='9'))
{
freqTable[chDigit-48]++;
}
}
}
}
public long[] GetFreq()
{
long longFreqTableReturn[] = new long[10];
CalculateFrequencies();
for (int iLoop=0; iLoop<10; iLoop++)
{
longFreqTableReturn[iLoop] = freqTable[iLoop];
}
return(longFreqTableReturn);
}
public static void main(String args[])
{
int iNums[] = { 1234,2345,3456,4567,5678,6789,7890,8901,9012};
DigitStats digitStats = new DigitStats(iNums);
long freqTable[] = digitStats.GetFreq();
System.out.println("----------------------------------------");
System.out.println(" DIGIT FREQ ");
System.out.println("-----------------------------------------");
for (int iLoop=0; iLoop<10; iLoop++)
{
System.out.println(" " + iLoop + " " + freqTable[iLoop]);
}
}
public void Clear()
{
A=null;
freqTable=null;
}
}

Rob S. answered 01/21/21
B.A. in Computer Science from Amherst College
In this static void method, you can create a new array of ints with a length of 10. Let's call that array counter. Each index of the array will represent the number of times each number, 0-9, has been found.
Use a for loop to iterate through each index of the parameter array, and increment the appropriate index of counter. For instance, if you encounter a 5 in the parameter array, increase counter[5] by 1. If you encounter a 1, increase counter[1] by 1.
Once you've gone through the entire parameter array in this fashion, you'll have essentially counted the number of occurrences of each integer; the number of occurrences will be held in counter.
Lastly, print out the value of each index of counter!
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Patrick B.
01/21/21