I created a program to find the mode. Then made it print the mode in brackets like "1 3 [5] 4 [5]" but when there is no mode in the array list it declares the first value as the mode, like "[1] 3 4 5". I don't want it to show brackets on first integer if there is no mode.
public static int mode(int[] array) {
int mode = array[0];
int maxCount = 0;
for (int i = 0; i < array.length; i++) {
int value = array[i];
int count = 1;
for (int j = 0; j < array.length; j++) {
if (array[j] == value)
count++;
if (count > maxCount) {
mode = value;
maxCount = count;
}
}
}
return mode;
}
Then I print it this way:
int[] array = ...
int mode = mode(array);
boolean first = true;
for (int elt : array) {
// print separator unless it's the first element
if (first) {
first = false;
} else {
System.out.print(' ');
}
if (elt == mode) {
System.out.print(elt);
} else {
System.out.print('[');
System.out.print(elt);
System.out.print(']');
}
}
System.out.println();
ifconditions).