Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrences of each digit in number using arrays

Tags:

java

arrays

I need to write a program using arrays, which takes a number and returns the number of incidents of each digit within that number. I think I may be overcomplicating things here.

import java.util.*;
class Exercice7 {

  public static void main(String [] args) {
    Scanner sc = new Scanner(System.in);

    System.out.println("Veuillez saisir un nombre naturel:");   // Get number

    int n = sc.nextInt();                                       // Store number as n

    String str = Integer.toString(n);                           // Store n as string

    int length = str.length();                                    // Store string length as length

    int arr[] = new int[length];                                // Declare array with as many elements as n has digits

    int digit[] = {0,1,2,3,4,5,6,7,8,9};                        // Declare array with the digits to look for

    int count = 0;                                                // Number of occurences of each digit

    for (int i=(length-1); i>=0; i--) {                         // Fill array with digits from number input
        while (n>0) {
            arr[i]= n%10;
            n = n/10;
        }
    }

    for (int j=0; j<10; j++) {
        count = 0;
        for (int i=0; i<length; i++) {
            if (arr[i]==digit[j]) {
                count++;
            }
        }
        if (count>0) {
        System.out.println(digit[j] + " occurs " + count + " times.");
        }
    }
  }
}

This code only returns the number of 0s and 1s and it's wrong anyway. Could someone push me in the right direction?

like image 854
ktouchie Avatar asked Sep 25 '22 23:09

ktouchie


1 Answers

Declare array with ten elements ([0..9]) - there you will have occurences of each digit in your number. Simply using counts[3] will get you number of occurences of digit 3.

Then you just iterate over string number and read next char as integer and increase counter. This way you have only one loop. For example, having 3 in your number, you use counts[3]++.

like image 84
deem Avatar answered Sep 28 '22 23:09

deem