2

The problem is: Write a program that reads integers between 1-100 and counts the occurrences of each. Assume the input ends with 0. If the number occurs more than once the plural "times" is used in the output. Here is a sample run of the program:

2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time

I have fixed the read integer in my code to no longer be i but a separate variable "index" and understand why I am receiving the out of bounds exception, but I am kind of thick and don't understand how to fix it at the same time as add a sentinel value of 0.

import java.util.Scanner;

public class countNumberOccurrence{
  public static void main(String args[]){

  int[] numbers = new int[100];
  inputArray(numbers);

  }

  public static void inputArray(int[] myList){
    Scanner input = new Scanner(System.in);
      System.out.print("Enter integers from 1-100 (input 0 value to end inputs): ");
      int index = 0;
      for(int i = 1; i < myList.length - 1; i++){
        if(i > 0){
          index = input.nextInt();  
          myList[index-1]++;  
        }

        if(myList[index-1] > 1)
          System.out.println(index + " occurs " + myList[index-1] + " times ");
        else
          System.out.println(index + " occurs " + myList[index-1] + " time ");
      }             

  }

}
user3325959
  • 31
  • 1
  • 1
  • 3

5 Answers5

4

Since you say in a comment you can't do it the proper idiomatic way:

The proper logic for detecting in input of a 0 and ending the application would be:

int nextInt;
while ((nextInt = input.nextInt()) != 0)
{
    // do your logic here
}
// print your output here

This is the proper way to handle the input.

Never work with raw arrays if you don't have to!

Always use the appropriate java.util.collections class and iterate with a for/each or the proper Iterator and you won't have these one off errors.

What you are looking for is called a Multimap

Here is a JDK only solution:

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class Q21871053
{
    public static void main(final String[] args)
    {
        final Random rnd = new Random();

        final Map<Integer, AtomicInteger> counter = new HashMap<Integer, AtomicInteger>()
        {
            @Override
            public AtomicInteger get(final Object key)
            {
                if (!super.containsKey(key)) { super.put((Integer) key, new AtomicInteger(rnd.nextInt(100))); }
                return super.get(key);
            }
        };

        final AtomicInteger nextInt = new AtomicInteger(rnd.nextInt(100));
        while (nextInt.get() != 0)
        {
            counter.get(nextInt.get()).incrementAndGet();
            if (counter.size() > 1000) { nextInt.set(0); } // limit the run to 1000 numbers
            else { nextInt.set(rnd.nextInt(100)); }
        }

        for (final Integer i : counter.keySet())
        {
        final AtomicInteger integer = counter.get(i);
        final String format = integer.get() > 1 ? "%d occurs %s times\n" : "%d occurs %s time\n";
        System.out.format(format, i, integer);
        }
    }
}

Here is a sample output:

3 occurs 43 times
98 occurs 16 times
64 occurs 35 times
36 occurs 27 times
37 occurs 19 times
7 occurs 58 times
76 occurs 48 times
77 occurs 40 times
41 occurs 68 times
46 occurs 5 times
13 occurs 100 times
14 occurs 15 times
51 occurs 85 times
17 occurs 40 times
85 occurs 16 times
18 occurs 97 times
25 occurs 10 times
24 occurs 12 times
29 occurs 14 times
91 occurs 2 times

Google Guava has a great implementation of a Multimap.java

@Override
public void functionToBeRateLimited(@Nonnull final String caller)
{
    // do some stuff every time here
    super.timesCalled.get(caller).incrementAndGet();

    // do some stuff only after a certain time has elapsed since the last time it was done
    if (LIMITER.get(caller).tryAcquire())
    {
        System.out.println(String.format("%s Called Rate Limited Logic up to 2 times a second ( 500 ms )", caller));
    }
}
  • I am not able to use things like that for my class assignment, basically I simply need to fix my code to add a sentinel value of 0 and get my read integer or index back between 1-100 – user3325959 Feb 19 '14 at 04:59
  • Well this is the way you would do it if you were working on a project for a company, or asked to do this on a whiteboard in an interview. Thanks to whomever for the down vote for learning the idiomatic way to do this in plain Java and the Guava library. –  Feb 19 '14 at 05:08
3

Jarrod gave a great answer, but if you have certain assignment specifications, make sure to list them.

Edited this, sorry for that mistake. Missed that you assigned index in the if block. The out of bounds issue arises when the user inputs 0 to end input. Even if the user is done, you try to insert into the array. So put an if statement to check for the 0.

int index = 0;
  for(int i = 1; i < myList.length - 1; i++){
    if(i > 0){
      index = input.nextInt();  
      if (index > 0 && index < myList.length)
           myList[index-1]++;
      else
        break;  
    }

Now this will work, but it's not the best style. A for loop is not the best choice here because you don't know how many numbers the user will input. This will fix your out of bounds issue, but there are a few other issues with your implementation. Fix this first and then work on the rest of the code.

Inertiatic
  • 1,270
  • 1
  • 9
  • 12
  • Well the out of bounds issue I am getting comes from trying to input a 0 value, which sets the index to 0 and therefore creates the issue. I don't know how to create a working sentinel value of 0 to end the user input but increment the other numbers. – user3325959 Feb 19 '14 at 05:46
  • Made a mistake, check the edit. – Inertiatic Feb 19 '14 at 06:02
3
package deneme;

import java.util.Scanner;

public class CountOccuranceNumbers {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);

        int[] number = new int[100];

        System.out.print("Enter the integers between 1 and 100: ");
        for (int i = 0; i < number.length; i++) {
            int a = input.nextInt();
            number[a] += a;
            if (a == 0)
                break;
        }
        for (int i = 1; i < number.length; i++) {
            if (number[i] != 0) {
                if (number[i] / i > 1)
                    System.out.println(i + " occurs " + number[i] / i + " times");
                else
                    System.out.println(i + " occurs " + number[i] / i + " time");               }
        }
    }
}
Will
  • 11,276
  • 9
  • 68
  • 76
2

I think your problem is in this line:

if(myList[index-1] > 1)
      System.out.println(index + " occurs " + myList[index-1] + " times ");

If index is 0 you will be trying to access the -1 element of the array which is out of bounds. Try this instead:

if(index>0){
    if(myList[index-1] > 1)
      System.out.println(index + " occurs " + myList[index-1] + " times ");
    }
    else
      System.out.println(index + " occurs " + myList[index-1] + " time ");
}

This makes it so the line won't try and access the -1 element if your index is 0.

Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
-1
public class q7 {

    public static void main(String[] args) {
        int arr[] = {6, 22, 20, 11, 5, 18, 18, 16, 30, 9, 10, 10, 11, 5, 18, 18, 16};
        for (int i = 0; i < arr.length; i++) {
            int count = 0;
            for (int j = 0; j < arr.length; j++) {
                if (arr[i] == arr[j])
                  count++;
            }
            System.out.println(arr[i] + "\toccures\t" + count + " times");
        }
    }
}
5gon12eder
  • 24,280
  • 5
  • 45
  • 92
Srajesh
  • 11
  • 2
    Welcome to SO. Please indent code with four spaces to make it display nicely. See [here](https://stackoverflow.com/editing-help#code) for more information. If you want to improve your answer, consider adding prose alongside your code that explains why your suggestion solves the problem and how it does so. – 5gon12eder Oct 03 '14 at 03:31