The number of instances of each digit using arrays

I need to write a program using arrays that takes a number and returns the number of incidents of each digit in that number. I think I can be something like this.

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 numbers 0s and 1s, and in any case it is wrong. Can someone push me in the right direction?

+5
source share
3 answers

Declare an array with ten elements ([0..9]) - there you will have the numbers of each digit in your number. Just using counts[3] , you get the number of occurrences of the digits 3 .

Then you just iterate over the line number and read the next char as an integer and increment the counter. This way you only have one cycle. For example, having 3 in your number, you use counts[3]++ .

+4
source

you can try converting to String and read every char

 int counts[] = {0,0,0,0,0,0,0,0,0,0}; int myNumber=123222;//example String string=""+myNumber; //converting integer to String for(int i=0;i<string.length();i++){ try{ int n=Integer.parseInt(string.charAt(i)+"") counts[n]=counts[n]+1; }catch(Exception e){} } 

then print it:

 for (int i=0; i<counts.length; i++) { System.out.println(i + " occurs " + counts[i] + " times."); } 
0
source

Thank you deem for your reply. I did not quite understand what you had in mind, but it helped me to get on the right path:

 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 num = sc.nextInt(); //* Store number as n */ String str = Integer.toString(num); //* Store n as string *// char digit[] = {'0','1','2','3','4','5','6','7','8','9'}; int count = 0; for (int i=0; i<10; i++) { for (int j=0; j<(str.length()); j++) { if (str.charAt(j) == digit[i]) { count++; } } if (count>0) { System.out.println(digit[i] + " apparait " + count + " fois."); count = 0; } } } } 

This may not be the easiest way, but it works! Feel free to add additional comments if you want to make improvements to the code.

0
source

Source: https://habr.com/ru/post/1238121/


All Articles