Home > Back-end >  How to show only occurrences of numbers user input in java?
How to show only occurrences of numbers user input in java?

Time:04-10

I'm new to programing and trying to solve this problem, but have no idea what I did wrong.

The program is supposed to take user input until 0 is entered and after that, print out information of occurrences of numbers user input - and here is my problem.

The program I wrote shows occurrences of all numbers (up to max number that can be input), not only those that user wrote.

My code:

package numbers;

import java.util.Scanner;

public class Numbers {

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

        int[] occurences = new int[11];

        int num = scan.nextInt();
        while (num > 0 && num <= 11) {
            occurences[num]  ;
            num = scan.nextInt();
        }
        for (int i = 0; i < 11; i  ) {
            System.out.print("Value: "   i   " Occurences: "   occurences[i]   " ");
        }
    }
}

CodePudding user response:

Use if statement to print only numbers with occurences higher than 0.

Side notes:

  1. Array values initialization is not needed:
for (int i = 0; i < 11; i  ) {
   occurences[i] = 0;
}

Value at each index is already 0, check this question.

  1. While loop condition, does not make much sense
while (num > 0 && num <= 11) {
   occurences[num]  ;
   num = scan.nextInt();
}

Array size is 11, meaning indexes range from 0 to 10 inclusive. Since you allow input 11, you will get ArrayIndexOutOfBoundsException.

CodePudding user response:

You can make use of map.

    Map<Integer, Integer> occ = new HashMap<>();

    int num = scan.nextInt();
    while (num > 0 && num <= 11) {
        occ.put(num, occ.getOrDefault(num, 0) 1);
        num = scan.nextInt();
    }

    for(int i : occ.keySet()){
        System.out.print("Value: "   i   " Occurences: "   occ.get(i)   " ");
    }

CodePudding user response:

if the occurrence is = 0 don't print it.

  • Related