例如,我只能用一个数字来完成 3,4,5,2,3 程序检测到模式为 3 但问题是当有多种模式并且程序仅检测到第一个重复的模式时 例如 3,3,4,4,5,6 它只会检测到 3 作为模式
这是代码
import javax.swing.*;
public class mode
{
public static void main (String args[])
{
JOptionPane.showMessageDialog(null,"This program will show below the mode ");
int counter = 0;
String cant,dat;
int maximumtimesthatisrepeated = 0;
double mode = 0;
cant=JOptionPane.showInputDialog(null,"Enter the amount of data to be registered:");
counter =Integer.parseInt(cant);
double[] DAT = new double[counter];
for (int i = 0; i < counter; i++)
{
dat=JOptionPane.showInputDialog(null,"Enter data: ");
DAT[i] =Double.parseDouble(dat);
}
for (int i = 0; i < DAT.length; i++) {
int timesthatisrepeated = 0;
for (int j = 0; j < DAT.length; j++) {
if (DAT[i] == DAT[j]) {
timesthatisrepeated++;
}
}
if (timesthatisrepeated > maximumtimesthatisrepeated) {
mode = DAT[i];
maximumtimesthatisrepeated = timesthatisrepeated;
}
}
JOptionPane.showMessageDialog(null,"The mode is " + mode +" and repeats "+maximumtimesthatisrepeated+"times");
}
}
最佳答案
问题:
您的代码只能检测第一个模式,因为您只测试较大模式,而模式只能保存一个值。
解决方案:
在最后的 if 语句中,您还必须检查是否存在相等情况,并且您的模式变量需要能够保存多个值。
示例:
double mode = 0; //replace this with line below
ArrayList<Double> mode = new ArrayList<>();
添加导入
import java.util.ArrayList;
像这样修改你的 if 语句:
if (timesthatisrepeated > maximumtimesthatisrepeated) {
// mode = DAT[i]; deprecaded line
mode.clear();
mode.add(DAT[i]);
maximumtimesthatisrepeated = timesthatisrepeated;
} else if (timesthatisrepeated == maximumtimesthatisrepeated) { // checks for additional modes
if (!mode.contains(DAT[i])) { // recognices duplicates
mode.add(DAT[i]);
}
}
注意:
为了简单起见,我使用了 ArrayList,因为它提供了 .add() 、 .clear() 和 .contains() 实现。也可以使用普通数组,但是您必须手动编写此操作。
模式的数量可以通过mode.size()
读取。
(抱歉拼写或语法错误:))
关于java - 我如何制作多种模式以及程序检测其是双峰还是三峰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49623564/