View difference between Paste ID: dvTvAjKP and XnFzLjv5
SHOW: | | - or go back to the newest paste.
1
public static void main(String[] args) {
2
	
3-
	char[] array = new char[20];
3+
	char[] array = new char[20]; // our array
4-
	Scanner sc = new Scanner(System.in);
4+
	Scanner sc = new Scanner(System.in); 
5
	
6
	for (int i = 0; i < 20; i++)
7
	{
8-
		array[i] = sc.next().charAt(0);
8+
		array[i] = sc.next().charAt(0); // scanning input from the user
9
	}
10
	
11-
	System.out.println(mostCommon(array));
11+
	System.out.println(mostCommon(array)); // printing the most common character
12
	
13
	sc.close();
14
15
}
16
17-
public static char mostCommon(char[] array) {
17+
// this function gets the array and returns the most common character
18-
	int max = -1;
18+
public static char mostCommon(char[] array)
19-
	int index = -1;
19+
{
20
	int max = -1; // will hold the max number of occurences
21
	int index = -1; // will hold the index of the most common character
22
	
23-
		int current = countTimes(array, array[i]);
23+
	// we go through the array and find the number of occurences for each item. 
24-
		if (current >= max)
24+
	// we compare it to max and update it every time (if needed). also we update the index.
25
26-
			max = current;
26+
	for (int i = 0; i < array.length; i++) 
27-
			index = i;
27+
28
		int current = countTimes(array, array[i]); // this variable holds the no. of occurences for the current item.
29
		if (current >= max) // if the current item is more common than the max 
30
		{
31-
	return array[index];
31+
			max = current; // we update the max to be the current value
32
			index = i; // and we update the index so we can know where is the most common item.
33
		}
34-
public static int countTimes(char[] array, char c) {
34+
35-
	int count = 0;
35+
	// by the end of the loop, "index" will hold the index of the most common character. all we need to do is return it.
36
	return array[index]; // we return the most common character.
37
}
38-
		if (array[i] == c)
38+
39-
			count++;
39+
// this function gets an array and a character and returns the number of occurences of the char in the array.
40
41
public static int countTimes(char[] array, char c)
42-
	return count;
42+
{
43
	int count = 0; // counter variable
44
	for (int i = 0; i < array.length; i++)
45
	{
46
		if (array[i] == c) // if the character appears
47
			count++; // increment the counter
48
	}
49
	
50
	return count; // return the number of times it appears.
51
}