假设我有10个随机生成的数字组成的数组。然后将这些数字放入列表中。如:
int[] fams = new int[4];
System.out.println("Number of families with 2 children: " + fams[0]);
System.out.println("Number of families with 3 children: " + fams[1]);
System.out.println("Number of families with 4 children: " + fams[2]);
System.out.println("Number of families with 5 or more children: " + fams[3]);
然后我必须说:
System.out.println("The most common number of children was " + common + ".");
我尝试了代码
int common = 0;
for(int i = 0; i < fams.length; i++) {
if(common < fams[i]) {
common = fams[i];
但是,这将输出最常见的fams编号(显然是这样)。我需要的是最常见的孩子人数。例如,如果2有5个家庭(输入10),则我需要数字2作为输出,而不是5。感谢您的帮助!
最佳答案
您需要同时跟踪fams
数组中的最高元素和该元素的索引。该索引是您要寻找的。
int common = 0;
int commonIndex = -1;
for(int i = 0; i < fams.length; i++) {
if(common < fams[i]) {
common = fams[i];
commonIndex = i;
}
}
在循环结束时,
commonIndex
将保存您需要的内容。