0

My code is supposed to prompt the user for an integer and count the occurrences of each digit in the integer. But it outputs nothing. Please help and here's my code.

import java.util.Scanner;

    public class NumberCounts {

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

         int arr [] = new int [10];
         int num;
         int outcome;

         System.out.println(" Enter a number: "); 
         num = scan.nextInt();

         while ( num != 0){
             outcome = num % 10;
             arr[num % 10]+=1;
             num /= num;
         }

         for ( int i = 0; i <= arr.length; i++){
             System.out.println(i + " : " + arr[i]);
         }

     }
}

1 Answers1

3

Inside your while loop, you are dividing num by itself, then assigning the result back to num. This will make num equal to 1 forever. Change it to

num /= 10;

which will remove the last digit.

Also, you already calculated the last digit and stored the result in outcome. You might as well use it:

arr[outcome]+=1;

Then, when you get to the loop to print the array, in the condition, always use < an array length to stop after processing the last index length - 1. This will prevent the ArrayIndexOutOfBoundsException that is waiting to show up.

for (int i = 0; i < arr.length; i++){
rgettman
  • 176,041
  • 30
  • 275
  • 357