By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,650 Members | 1,368 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,650 IT Pros & Developers. It's quick & easy.

How do I print the occurrence of the number once?

P: 2
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


Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2. public class Histogram{
  3.     public static void main(String args[]){ 
  4.         Scanner input = new Scanner(System.in); 
  5.  
  6.         int count = 0;
  7.  
  8.         System.out.print("How many integers should I collect? ");
  9.         int[] integers = new int[input.nextInt()]; 
  10.  
  11.         count++;
  12.  
  13.         for (int i = 0; i < integers.length; i++) { 
  14.             System.out.print( + (i + 1) + ": ");
  15.             integers[i] = input.nextInt(); 
  16.  
  17.         }
  18.         java.util.Arrays.sort(integers); 
  19.         System.out.println("");
  20.         for(int i = 0; i < integers.length; i++) { 
  21.             System.out.println(+ integers[i] + ": " + count); 
  22.  
  23.  
  24.     }
  25.     }
Apr 28 '13 #1
Share this Question
Share on Google+
1 Reply


Rabbit
Expert Mod 10K+
P: 12,421
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.
Apr 29 '13 #2

Post your reply

Sign in to post your reply or Sign up for a free account.