数组的模式 - Java 中的方法



所以我有这个模式代码,这是我为我的硬件编写的,我需要弄清楚如何使输出看起来不那么混乱。

输入示例:

2, 2, 2, 3, 3, 3

输出将完全相同(这是模式(,但我需要它只是23而不重复。 下面是代码本身:

public static void runMode(int[] data) 
{
int maxValue = -1;
int maxCount = 0;
int p = 0;
for(int i = 0; i < data.length; i++)
{
int count = 0;
for(int j = 0; j < data.length; j++)
{
if(data[j] == data[i])
{
count++;
}
}
if(count > maxCount)
{
maxCount = count;
maxValue = data[i];
}  
}
System.out.print("Mode: ");
for(int i = 0; i < data.length; i++)
{
int count = 0;
for(int j = 0; j < data.length; j++)
{
if(data[j] == data[i])
{
count++;
}
}
if(count == maxCount)
{
System.out.print(data[i] + ", ");
}
}
}

编辑:不幸的是,HashMapArrayList不允许在作业中使用。

这可能看起来有点复杂,但我认为如果您在System.out.print("Mode: ");我的演示中显示的行之后编辑代码,那么它应该为您提供所需的输出。这是演示:

System.out.print("Mode: ");
int[] dataCounted = new int[data.length]; // This array will hold the values that are the mode
int value = -1; // Value of the number you're testing for, not how many of the number there is
int index = 0; // Index for the dataCounted array
for (int i = 0; i < data.length; i++)
{
value = data[i];
int count = 0;
for (int j = 0; j < data.length; j++)
{
if (data[j] == data[i])
{
count++;
}
}
if (count == maxCount)
{
boolean used = false;
for (int j = 0; j < index; j++) 
{
if (value == dataCounted[j]) 
{
used = true;
}
}
if (!used) 
{
dataCounted[index++] = value;
System.out.print(data[i] + ", ");
}
}
}

最新更新