# Thread: inputs numbers then outputs how many time a particular number appears

1. Member Join Date
Dec 2009
Posts
8
Rep Power
0

## inputs numbers then outputs how many time a particular number appears

Ok, this is what my teacher wants me to do:

Write a program that reads a set of positive integers and outputs how many times a particular number appears in the list. You may assume that the data set has at most 100 numbers and -999 marks the end of the input data. The numbers must be output in increasing order. For example, for the data:

15 40 28 62 95 15 29 13 62 65 48 95 62 65 95 95 -999

The output is:
Number Count
13_____1
15_____2
28_____2
40_____1
48_____1
62_____3
65_____3
95_____4

and this is what I came up with
Java Code:
```import java.io.*;
import java.util.*;
public class Numbers{
public static void main(String[]args)throws Exception{

Scanner sc = new Scanner(System.in);
int[] number = new int;
int[] counter = new int;
int i, j, c=0;

for(i = 0;i<number.length; i++){
System.out.print(" ");
number[i] = sc.nextInt();
if (number[i]== -999){
break;
}
}
Arrays.sort(number);
System.out.println("Numbers\tCounts");
for (i=2; i<number.length;i++){

if (i!=0){
if(number[i]==number[i-1]){
do{
i=i+1;
counter[i-2]=c+1;
}while(number[i]==number[i-1]);
}
}
System.out.println(number[i]+"\t"+counter[i-2]);

}
}
}```
I need some help because for some reasons.. this program doesn't do the thing I want it to do. And I'm out of ideas! :(
Please, even a little help would be much appreciated. 2. ## Use a TreeMap<Integer, Integer> and add a number to it like this:

Java Code:
```private TreeMap<Integer> map= new TreeMap<Integer, Integer>();
...
Integer count= map.get(i);
if (count == null)
count= Integer.valueOf(0);
map.put(i, count+1);
}```
kind regards,

Jos
Last edited by JosAH; 12-18-2009 at 06:58 PM. 3. Member Join Date
Dec 2009
Posts
8
Rep Power
0

## ok... thanks... that was very useful... (if i was a professional programmer...maybe...)
Sorry. I forgot to mention, I've just started learning programing. And still doesn't know how to use methods and stuffs like that.. so, if it isn't too much for you, can you please make it a little simplier so that a noob (like myself here) can understand? :)
Thank you. 4. ##  Originally Posted by koji_kun ok... thanks... that was very useful... (if i was a professional programmer...maybe...)
Sorry. I forgot to mention, I've just started learning programing. And still doesn't know how to use methods and stuffs like that.. so, if it isn't too much for you, can you please make it a little simplier so that a noob (like myself here) can understand? :)
Thank you.
If I had to take out that map and use ordinary arrays, the code would become more complicated; too complicated for a beginner.

kind regards,

Jos 5. Senior Member Join Date
Feb 2009
Posts
312
Rep Power
12

## Taking a quick glance at your code I notice a couple things:

First, When you are retrieving the next Number from the scanner, don't immediately save it. Instead make a new int and perform the checks on that for the -999. Your current code will save the -999 into the array.

Java Code:
```     int nextInt = sc.nextInt();
if (nextInt == -999) {
break;
} else {
number[i] = nextInt;
}```
Your main issue is in your final for block with the do while. I would recommend going through that and try to figure out exactly what is going on.

Why exactly do you start off i at 2? This seems like it was done just to get the initial ArrayOutOfBoundsException to not occur but will ignore 2 numbers if the user did enter 100. That should start off at 0 and your counter and checks need to be redone. 6. Member Join Date
Dec 2009
Posts
24
Rep Power
0

## maybe something like this:
Java Code:
```Arrays.sort(number);
System.out.println("Numbers\tCounts");
for (int i=0; i<number.length;i++)
{
int number = number[i];
int count = 0;
while(number[i]==number && i<number.length)
{
count++;
i++;
}
System.out.println("Number: "+number+" Count: "+count);

}``` 7. Member Join Date
Dec 2009
Posts
8
Rep Power
0

##  Originally Posted by JosAH If I had to take out that map and use ordinary arrays, the code would become more complicated; too complicated for a beginner.

kind regards,

Jos
why do you have to make it too complicated? my teacher said it is just a simple array problem.. (but not as easy as I thought it was :( ) Originally Posted by StormyWaters Taking a quick glance at your code I notice a couple things:

First, When you are retrieving the next Number from the scanner, don't immediately save it. Instead make a new int and perform the checks on that for the -999. Your current code will save the -999 into the array.

Java Code:
```     int nextInt = sc.nextInt();
if (nextInt == -999) {
break;
} else {
number[i] = nextInt;
}```
great, I'll be using this then.. thanks.. Originally Posted by StormyWaters Your main issue is in your final for block with the do while. I would recommend going through that and try to figure out exactly what is going on.
that's what i've been trying to figure out.. lol.. Originally Posted by wtd_nielsen maybe something like this:
Java Code:
```Arrays.sort(number);
System.out.println("Numbers\tCounts");
for (int i=0; i<number.length;i++)
{
int number = number[i];
int count = 0;
while(number[i]==number && i<number.length)
{
count++;
i++;
}
System.out.println("Number: "+number+" Count: "+count);

}```
this code didn't work..
hmm.. ok, so here's my main problem:
How do I get it to print a number just once if it was entered more than once?:confused: 8. Member Join Date
Nov 2009
Posts
12
Rep Power
0

## I have just glanced over the code and i think that you could do a check using nested for loops (for loop inside another for loop).

such as

Java Code:
```int compare = 0;

for(int i = 0; i < number.length; i++)
{
for(int j = 0; j < number.length; j++)
{
compare = number[i];
if(compare != number[j])
{
System.out.println(number[j]);
}
}
}``` 9. ##  Originally Posted by koji_kun why do you have to make it too complicated? my teacher said it is just a simple array problem.. (but not as easy as I thought it was :( )
Too complicated? Look at all the code posted in this thread: all solutions that use arrays have to bend themselves over backwards to accomplish what you want; a simple Map<Integer, Integer> and my add( ... ) method solves it all in a few lines.

kind regards,

Jos 10. gcampton Guest

##  Originally Posted by JosAH Too complicated? Look at all the code posted in this thread: all solutions that use arrays have to bend themselves over backwards to accomplish what you want; a simple Map<Integer, Integer> and my add( ... ) method solves it all in a few lines.

kind regards,

Jos
He was referring to your code using simple arrays not the tree map you posted, you said it would be too complicated.

------------------------------------------------

Ok, now lets try and solve this in english. Pseudocode is generally the best way to figure out how our code should look.

stage 1:
2. count number of times each number appears
3. output results.

stage 2:
1.1: read in each number and store in an array of size 100 only up to -999.
If numbers occur beyond this point(-999) they will not be processed.

2.1: using a for loop, check this element against every other element incrementing a counter of number of times this appears.
2.2: store the count in our counter array.
2.3: keep looping steps 2.1-2.2 until value -999 is reached.

3.1: This output is where it can get tricky as for example if we have the number 555 entered 99 times and 666 once, then we don't really want 99 print statements telling us that. I think "simple exercise" is a little understatement. But all we would do here is traverse the array and only output each "individual" element. numbers that have already been displayed won't be displayed again. Perhaps a boolean/or another counter can help us achieve this.

stage 3: we start expanding on the ideas above, with a little code.
Last edited by gcampton; 12-20-2009 at 05:17 AM. 11. ##  Originally Posted by gcampton He was referring to your code using simple arrays not the tree map you posted, you said it would be too complicated.
Yes, if you take out the map the code would become too complicated; for a sketch of a proof see all the clumsy array solutions in this thread. It is beyond me why people don't want to use an object that is made for the job but prefer to keep on doodling with arrays. Maybe it's the fear for the unknown? If so that explains why there is so much clumsy code in the world. Or maybe it's just a homework restriction that severely cripples the possible solutions.

kind regards,

Jos
Last edited by JosAH; 12-20-2009 at 09:49 AM. 12. ##  Originally Posted by gcampton 3.1: This output is where it can get tricky as for example if we have the number 555 entered 99 times and 666 once, then we don't really want 99 print statements telling us that. I think "simple exercise" is a little understatement. But all we would do here is traverse the array and only output each "individual" element. numbers that have already been displayed won't be displayed again. Perhaps a boolean/or another counter can help us achieve this.
Better sort the numbers first, find the runlengths and output those lengths for the associated numbers; e.g. the original series:

15 40 28 62 95 15 29 13 62 65 48 95 62 65 95 95 -999

would end up sorted like this:

13 15 15 28 29 40 48 62 62 62 65 65 95 95 95 95

Counting the lengths of the different numbers results in this:

1 2 1 1 1 1 3 2 4

I still find this much more clumsy than a simple Map<Integer, Integer>, it does the job for you on the fly.

kind regards,

Jos 13. gcampton Guest

## yes I agree with you JosAH but people still need to learn how these things work

and I think that's probably a better way than what I suggested. sorting to occur before step 2.1 and then simply count the runs.
Last edited by gcampton; 12-20-2009 at 12:58 PM. 14. Member Join Date
Feb 2009
Posts
92
Rep Power
0

## A map has a search key and stores a value at that key. The value is stpred and retrieved according to the key. The key can be an integer or a string, i.e. 1, "one", or "abc1". Each key must be unique. For the stated problem, an array may work just as well, and the coding is as simple. Just consider the index of the array as the key. If you reread some of the above posts, you will see how to do some of what is in this code.

The OP leaves one question open. The size of the data set has been defined, how about the range of input values? I'm seeing an implication that the range is 0 to 100, and that an array solution is expected as an exercise. If the range is small, a relative term that could be 10 0r 10000, an array will work nicely and meet the point of the exercise.

Java Code:
```flag = false
while(!flag){
input and parse integer
if(input != sentinal value and input count fewer than 100 ) // (-999)
countingArray[input] += 1;
else
flag = true;
end else
endwhile
for(each item in count array != 0)
print ("number: " + index + " was input " + array[index] + " times")```
Note that this outputs the list in sorted order. It's much what you would do with a map.

I'm omitting the overhead of input and parsing, but that has to be done anyway.

This is a beginning level forum. IMHO, it is not always a good idea to reach for classes that use data structures that are unfamiliar to the user when the point is probably to teach basic computer science and data structures. While the aspiring programmer will need to learn these other techniques, it will come in time. But the implication is that this is an exercise to learn the use of arrays and we need to help him get to the point the array solution really is simple. The map solution is much better if the values and counts are sparse (two inputs with a range of 0 to 1 million), but that is not usually the case for first level courses.

Best to show the clear and simple way at the rudimentary level, as gcampton suggests. I've left out the over head of reading the number, but seems to be understood in the OP..

Stormywaters is correct. Save your input into a temporary variable, then use that as the index, as in the psuedocode. 15. ##  Originally Posted by rdtindsm The OP leaves one question open. The size of the data set has been defined, how about the range of input values? I'm seeing an implication that the range is 0 to 100
All I'm seeing is that those numbers have to be positive; here are the original requirements:

Write a program that reads a set of positive integers and outputs how many times a particular number appears in the list. You may assume that the data set has at most 100 numbers and -999 marks the end of the input data.
I'm afraid a solution where the index of the array serves as a key is not applicable here.

kind regards,

Jos 16. Member Join Date
Dec 2009
Location
Rio de Janeiro
Posts
38
Rep Power
0

## I've seen several bugs in your code, man:

1. This one has been mentioned before:

Java Code:
```for(i = 0;i<number.length; i++){
System.out.print("Enter a number: ");
int actual = Integer.parseInt(sc.nextLine());
number[i] = sc.nextInt(); //you always insert -999 in the array.
if (number[i]== -999){
break;
}
}```
2. You only sort one array here

Java Code:
`Arrays.sort(number);`
That will not work since you have one array that has the numbers typed and another array that has the number of times each one has been typed. You need to find a way to sort both arrays.

3. This part:

Java Code:
`for (i=2; i<number.length;i++){`
will not work because number.length will always be 100 (which is the size of the array), you need an extra variable will will count the number of elements in the array and change number.length to this new variable.

ok? 17. Member Join Date
Dec 2009
Location
Rio de Janeiro
Posts
38
Rep Power
0

## And I don't like your teacher because he teaches you to think in Java like if you were programming in C... 18. Member Join Date
Feb 2009
Posts
92
Rep Power
0

## I agree that a tree map is the best overall solution that would be used in the real world. It keeps everything in a sorted order as entered. All you need is a foreach loop to print results.

We really don't know if there is a constraint that an array must be used. I always have it in the back of my mind that the intent of an assignment is to learn to use a specific structure.

If there is that constraint:

The code to use an array is not difficult. Just more of it for the coder.

Create an object that is a pair of (value, count).

public class Pair (
int value;
int count;
}

Then you have to write a comparator for the Array sorting routine.

From Array methods api.

sort(Object[] a, int fromIndex, int toIndex, Comparator c)

The comparator would be almost trivial to write.
compare(obj ob1, obj ob2) {
return compare (obj1.value, obj2.value)
}

So, rather than two arrays of primitives, you have one array of objects that can be sorted in your call to Array.sort(...);

You still have the overhead of searching through the array to update it correctly. 19. Member Join Date
Dec 2009
Posts
24
Rep Power
0

## I think you guys are missing a point. I think he is supposed to solve this problem with an array, because he need to learn how to work with arrays. You dont start with Maps if you are new to programming.

maybe this will work?
Java Code:
```                Arrays.sort(number);
System.out.println("Numbers\tCounts");
int x=0;
while (x<number.length)
{
int number1 = number[x];
int count = 0;
while(x<number.length && number[x]==number1)
{
count++;
x++;
}

System.out.println("Number: "+number1+" Count: "+count);

}``` 20. ## Hi Koji ;) Originally Posted by koji_kun Write a program that reads a set of positive integers and outputs how many times a particular number appears in the list. You may assume that the data set has at most 100 numbers and -999 marks the end of the input data. The numbers must be output in increasing order. For example, for the data:

15 40 28 62 95 15 29 13 62 65 48 95 62 65 95 95 -999

The output is:
Number Count
13_____1
15_____2
28_____2
40_____1
48_____1
62_____3
65_____3
95_____4
I've written the solution using simple arrays, for- and while loops. No methods or data structures needed. A simple bubble sort does the job. However, the given example output is problematic. I can only see one occurrence of 28 and two occurrences of 65 in that set. ;) My solution outputs:
Java Code:
```13_____1
15_____2
28_____1
29_____1
40_____1
48_____1
62_____3
65_____2
95_____4```
Can I post the solution? Others do not agree with this, but I feel that students learn best by example. ;) #### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•