【问题标题】:Needing help on printing mode in java在java中需要有关打印模式的帮助
【发布时间】:2021-05-31 16:02:36
【问题描述】:

我的任务是创建一个方法,该方法接受 Integer obj 的 ArrayList 的参数并打印出总和、平均值和众数。

我似乎不知道如何找到该模式。如果只有一种模式,它应该打印出数字,如果有多个(或无)模式,它应该打印出“没有单一模式”。我的方法只打印出“没有单一模式”。如何修复我的代码以打印出模式?

这就是我的代码:

public static void printStatistics(ArrayList<Integer> arr){
int sum = 0;
for(int i : arr){
  sum += i;
}
System.out.println("Sum: "+sum);
System.out.println("Average: "+(double)sum/arr.size());

int temp = 0, counter = 0, max = 0;
for(int j = 0; j < arr.size() - 1; j++){
  for(int k = j+1; k < arr.size(); k++){
    if(arr.get(j) == arr.get(k)){
      counter++;
      
      if(counter > max){
        max = counter;
        temp = arr.get(j);
      }
      if(counter == max){
        temp = -1;
      }
    }
  }
}
if(temp > 0){
  System.out.println("Mode: "+temp);
}
else if(temp < 0){
  System.out.println("Mode: no single mode");
}

}

【问题讨论】:

    标签: arraylist methods mode


    【解决方案1】:

    问题出在这里

    if(counter > max){
        max = counter;
        temp = arr.get(j);
    }
    if(counter == max){
        temp = -1;
    }
    

    您在第一个条件中将counter 的值分配给max,因此第二个if 条件即if(counter == max) 将始终为true,这导致temp 具有值@987654328 @ 满足 else if(temp &lt; 0)。这就是为什么您每次都将Mode: no single mode 作为输出。


    改变条件应该会给你想要的输出

    if(counter < max){
        temp = -1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 2011-02-23
      • 2022-11-28
      • 1970-01-01
      • 2015-10-13
      • 2021-01-29
      • 1970-01-01
      相关资源
      最近更新 更多