1

I want to create a program that counts the number of occurrence of integers from user input e.g. 121221315

0: 0 times

1: 4 times

2: 3 times

3: 1 times

4: 0 times... etc up until 9...

But my code reads e.g. 121221315 as a single integer and i need to find a way that can split each integers

Another issue is that I don't know how to stop the first for loop... I have no clue which condition to put in on how to stop the loop when the program finished reading the input... I have just started learning coding.. please help me with simple/easy codes!!

I have following code

import java.util.Scanner;

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

        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;
              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");               }
        }
    }
}

1
  • Whats about the javascript java thing? Thats not javascript. It's java! Commented Oct 4, 2017 at 11:29

1 Answer 1

1

If you are given and Integer, you can convert it to a String, split it in an array of Strings, and using stream with groupingBy make a map of occurrences.

 Integer a = 121221315;

 Map<String, Long> collect = Arrays.stream(String.valueOf(a).split(""))
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

That's of course if you are allowed to use java 8 features.

The map will contain occurrences of digits that exist at least once. Logically the rest of digits have 0 occurrences.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer! what if the user is to input the numbers? through keyboard
@SongPak, what do you mean ? This example is for numbers, String.valueOf(a) converts it to a string
like i wouldnt know the numbers given... i wouldnt know if the number will be 121221315... it could be somethingelse depending on the user input... maybe a = keyboard.nextInt(); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.