CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2012
    Posts
    17

    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!

  2. #2
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    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 code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured