How do I print the occurrence of the number once?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • maggiexoxo
    New Member
    • Apr 2013
    • 2

    How do I print the occurrence of the number once?

    my code asks the user for a number N
    then it asks the user again for N numbers
    it sorts the numbers ascending and print's it with the number of occurrences.

    prints:
    How many integers should I collect? 5
    1: 2
    2: 4
    3: 4
    4: 5
    5: 6

    2: 1
    4: 1
    4: 1
    5: 1
    6: 1

    how I want it to print:
    How many integers should I collect? 5
    1: 2
    2: 4
    3: 4
    4: 5
    5: 6

    2: 1
    3: 0
    4: 2
    5: 1
    6: 1


    Code:
    import java.util.Scanner;
    public class Histogram{
    	public static void main(String args[]){ 
    		Scanner input = new Scanner(System.in); 
    		
    		int count = 0;
    		
    		System.out.print("How many integers should I collect? ");
    		int[] integers = new int[input.nextInt()]; 
    		
    		count++;
    		  
    		for (int i = 0; i < integers.length; i++) { 
    			System.out.print( + (i + 1) + ": ");
    			integers[i] = input.nextInt(); 
    			
    		}
    		java.util.Arrays.sort(integers); 
    		System.out.println("");
    		for(int i = 0; i < integers.length; i++) { 
    		    System.out.println(+ integers[i] + ": " + count); 
    
    	
    	}
    	}
    }
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You only incremented your count once. What you need to do is insert or increment a new array based on whether or not it exists already.

    Comment

    Working...