0

So close to having this program working but I'm stuck. What I want it to do is simply print out the numbers that have actual occurrences, so if the user inputs : 1, 2, 3, 2, 6

It needs to display

1 - 1 times
2 - 2 times
3 - 1 times
6 - 1 times

What I'm actually getting with the same input is something like:

1 - 1 times
2 - 2 times
3 - 1 times
4 - 0 times 
5 - 0 times
6 - 1 times

I need to remove the case where there are no occurrences.

 import java.util.Arrays; 
 import java.util.Scanner;
 public class CountOccurrences
 {
      public static void main (String [] args)
      {
      Scanner input = new Scanner(System.in);

      //Create Array for numbers
      int numbers[] = new int[100];

      //Prompt user input
      System.out.println("Enter integers between 1 and 100: ");
       //For loop to continue input
       for (int i = 0; i < numbers.length; i++) {
            int next = input.nextInt(); 
               //Breaks loop if 0 is inputted
                if (next==0)
                  {
                     break; 
                       } 
            numbers[i] = next; 
                }

         //Calls on countInts method
       int[] count = countInts(numbers); 
         //Calls on display counts
       displayIntCount(count); 

      }  

     //Counts each instance of a integer
    public static int[] countInts(int[] ints)
    {
        int[] counts = new int[100];

        for(int i = 1; i <=counts.length; i++)
            for(int j=0;j<ints.length;j++)

                if(ints[j] == i)
                    counts[i-1]++;
        return counts;
    }

     //Displays counts of each integer
    public static void displayIntCount(int[] counts)
    {
          for (int i = 0; i < counts.length; i++)
            System.out.println((i+1) +" - " +counts[i] +" Times");
    }
}
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
Crichton
  • 3
  • 2

1 Answers1

2

Just use a simple if statement to check if counts[i] is not 0, like this:

public static void displayIntCount(int[] counts)
{
     for (int i = 0; i < counts.length; i++) {
          if (counts[i] != 0) {
              System.out.println((i+1) +" - " +counts[i] + " Times");
          }
     }
}
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
  • Thank you, for some reason I was under the impression that != wouldn't work as arrays haven't been friendly with boolean expressions. – Crichton Oct 25 '14 at 19:29
  • @Crichton I'm assuming you were having issues with `==`? FYI, [`==` behaves differently from what you would expect when used on objects; you would need to use `.equals()` in that case](http://stackoverflow.com/a/2772783/3991344). And for arrays, [`array1.equals(array2)` is the same as `array1 == array2`; you want `Arrays.equals(array1, array2)`](http://stackoverflow.com/q/8777257/3991344). But doing something like `array1[0] == array2[0]` (with an int array) or `array1[0].equals(array2[0])` should work fine. – Pokechu22 Oct 25 '14 at 19:33