我如何制作多种模式,程序检测其是双峰还是三峰

时间:2018-04-03 06:27:00

标签: java arrays

我只能用一个数字来做 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");
    }
}

1 个答案:

答案 0 :(得分:0)

<强>问题:
您的代码只能检测第一个模式,因为您只测试更大模式,模式只能保存一个值。

<强>解决方案:
在最后的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()实现。也可以使用普通数组,但是您必须手动编写此操作 模式的nuber可以通过mode.size()读取。

(对不起拼写或语法错误:))