I am working on an HW assignment that asks to write a method called count that determines the number of times a target value appears in an array. For example, if your array is [2, 3, 3, 3, 4, 6, 7, 8, 8, 9], the value 8 appears twice and the number 4 appears once. You should know that the method has two parameters and one return value. The code works but the problem that I am having is when I print the statement "The value x[i] appears count(x,x[i]) times" it repeats the same statement when it should only print the statement for each value. I need help on making it so it will only print the statement as long as the value is different from the one before it if it is the same as the value before it the code should skip and move on to the next value in the array until it prints everything.
import java.util.Arrays;
public class Q7 {
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
for (int i = 0; i < x.length; i ) {
System.out.println("The value " x[i] " appears " count(x, x[i]) " times.");
}
}
public static int count(int[] array, int target) {
int counter = 0;
for (int i = 0; i < array.length; i ) {
if (array[i] == target) {
counter ;
}
}
return counter;
}
}
Output:
[2, 3, 3, 3, 4, 6, 7, 8, 8, 9]
The value 2 appears 1 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 3 appears 3 times.
The value 4 appears 1 times.
The value 6 appears 1 times.
The value 7 appears 1 times.
The value 8 appears 2 times.
The value 8 appears 2 times.
The value 9 appears 1 times.
CodePudding user response:
in the case of your example (because the array is sorted), you can just change
for (int i = 0; i < x.length; i )
to
for (int i = 0; i < x.length; i = i count(x, x[i]))
It will skip duplicate items.
CodePudding user response:
You must somehow remember for which values you have already printed the message. there are several ways to do this. For example, you could sort your array and only output the message if you hit a value you didn't have yet while iterating. Another simple approach would be to add the elements to a set to get unique values of the array. Example with a set:
public static void main(String[] args) {
int[] x = { 2, 3, 3, 3, 4, 6, 7, 8, 8, 9 };
System.out.println(Arrays.toString(x));
Set<Integer> set = new HashSet<>();
for (int i = 0; i < x.length; i ) {
if(set.add(x[i])){
System.out.println("The value " x[i] " appears " count(x, x[i]) " times.");
}
}
}