Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String[] args) {
- char[] array = new char[20]; // our array
- Scanner sc = new Scanner(System.in);
- for (int i = 0; i < 20; i++)
- {
- array[i] = sc.next().charAt(0); // scanning input from the user
- }
- System.out.println(mostCommon(array)); // printing the most common character
- sc.close();
- }
- // this function gets the array and returns the most common character
- public static char mostCommon(char[] array)
- {
- int max = -1; // will hold the max number of occurences
- int index = -1; // will hold the index of the most common character
- // we go through the array and find the number of occurences for each item.
- // we compare it to max and update it every time (if needed). also we update the index.
- for (int i = 0; i < array.length; i++)
- {
- int current = countTimes(array, array[i]); // this variable holds the no. of occurences for the current item.
- if (current >= max) // if the current item is more common than the max
- {
- max = current; // we update the max to be the current value
- index = i; // and we update the index so we can know where is the most common item.
- }
- }
- // by the end of the loop, "index" will hold the index of the most common character. all we need to do is return it.
- return array[index]; // we return the most common character.
- }
- // this function gets an array and a character and returns the number of occurences of the char in the array.
- public static int countTimes(char[] array, char c)
- {
- int count = 0; // counter variable
- for (int i = 0; i < array.length; i++)
- {
- if (array[i] == c) // if the character appears
- count++; // increment the counter
- }
- return count; // return the number of times it appears.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement