CPT111-Week4
Exercise #4.1 Integer Frequency
Write a Java function/static method getFrequency(int[] input, int num) that takes as parameter an array of integers input and an integer num and returns the frequency of appearances of num in the array input.
For example, if input = [1, 2, 1] and num = 1, the function should return 2. And if num = 2, the function should return 1.
For example:
Ans:
public class IntegerFrequency {
public static void main(String[] args) {
int[] input = {1, 2, 1};
System.out.println(getFrequency(input, 2));
}
public static int getFrequency(int[] input, int num) {
int count = 0;
for (int j : input) if (j == num) count++; //Simplified For-Each Loop
return count;
}
}For-Each Loop Syntax
The syntax of the Java for-each loop is:
for(dataType item : array) {
...
}Here,
array - an array or a collection
item - each item of array/collection is assigned to this variable
dataType - the data type of the array/collection
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 tianyang
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果