gpt4 book ai didi

java - Java 中数组的模式 - 方法

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:40 24 4
gpt4 key购买 nike

所以我有为硬件分配编写的模式代码,我需要弄清楚如何使输出看起来不那么困惑。

输入示例:

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] + ", ");
}
}
}

关于java - Java 中数组的模式 - 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52377283/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com