[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 253
  • Last Modified:

not counting right

public class counting
{
    public static void main(String args[])
    {
        int responses[] = {10,3,1,2,6,4,8,5,9,9,7,8,6,8,6,3,10,3};
        int frequency[]= new int[11];
       
        // for each answer, select responses element and use that value
        // as frequency index to determine element to increment
       
        for(int answer = 0; answer < frequency.length; answer++)
        ++frequency[responses[answer]];
       
        System.out.print("Rating\tFrequency\n");
       
        // append frequencies to String system.out
        for(int rating = 1; rating < frequency.length; rating++)
        System.out.print(rating + "\t" + frequency[rating] + "\n");

    }
}

why is this not counting right?
0
m-jansen
Asked:
m-jansen
1 Solution
 
guitaristxCommented:
What should the correct output be?  I'm guessing:
1     1
2     1
3     3
4     1
5     1
6     3
7     1
8     3
9     2
10     2

(pardon the formatting)

If so, you'll want to (first) initialize your array members to zero.  This might be throwing it off.

Also, your actual "doing stuff" loop should look like this:

for(int i = 0; i < responses.length; i++)
     ++frequency[ responses[i] ];

If you look closely, you're not iterating through the entire array of responses.  Good luck!
0
 
m-jansenAuthor Commented:
I'm getting this out put when running posted 10:54AM class.

Rating      Frequency
1      1
2      1
3      1
4      1
5      1
6      1
7      1
8      1
9      2
10      1

I didn't understand how the loops worked so I was blinded.
Now I see it better.

And I'm getting output:

Rating      Frequency
1      1
2      1
3      3
4      1
5      1
6      3
7      1
8      3
9      2
10      2

thanx
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now