-
August 30th, 2012, 09:05 PM
#1
Counting Occurrences of Numbers
Having a problem trying to count the occurrences of numbers in an array!
The program is supposed to read integers between 1 and 100 and counts the occurrences of each.
The input ends with the user entering 0.
Here's what I've done:
Code:
import java.util.Scanner ;
public class Exercise06_03
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in) ;
int[] numbers = new int[100 + 1] ;
int data = 0 ;
int ocurrence = 0 ;
System.out.print("Enter integers between 1 and 100: ") ;
while((data = input.nextInt()) != 0)
{
numbers[data]++ ;
}
for(int m = 0 ; m < numbers.length ; m++)
{
for(int n = 0 ; n < numbers.length ; n++)
{
if(numbers[m] == numbers[n]) {
ocurrence++ ;
}
}
if(ocurrence > 1) {
System.out.println(numbers[m] + " occurs " + ocurrence + " times") ;
} else {
System.out.println(numbers[m] + " occurs " + ocurrence + " time") ;
}
}
}
}
Thanks in advance!
-
August 31st, 2012, 02:43 AM
#2
Re: Counting Occurrences of Numbers
Code:
while((data = input.nextInt()) != 0)
{
numbers[data]++ ;
}
That code it already keeping a count of the number of occurrences of each number entered, you don't need the inner loop with the occurrence variable. When printing out the results, just print out the non-zero values in the numbers array.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|