简体   繁体   English

尝试创建使用另一个数组+哈希图的信息填充数组的循环

[英]Trying to create loop that fills array using info from another array + hash map

I'm trying to prepare data to be used inside of a histogram. 我正在尝试准备要在直方图中使用的数据。 I want 2 arrays, one is all the temperatures from my highest and lowest collected temperature. 我想要2个阵列,一个是我收集的最高和最低温度中的所有温度。 The second array will contain the frequency of each temperature. 第二个数组将包含每个温度的频率。

int difference is the difference from the lowest and highest temp int difference是与最低和最高温度的差异

Array temp contains the temperatures collected Array temp包含收集的温度

HashMap map contains the frequencies collected of each temp HashMap map包含每个温度收集的频率

Array tempGaps contains the temperatures + every other temp that was not collected Array tempGaps包含温度+未收集的所有其他温度

Array finalTemps contains the frequency of each temp. Array finalTemps包含每个温度的频率。

The goal I hope to achieve is two arrays, one with all the temperatures, one with the frequencies of each and their index value is what corresponds them to eachother. 我希望实现的目标是两个阵列,一个具有所有温度,一个具有每个频率,它们的索引值就是它们彼此对应的值。

public void fillGaps() {
    int j = 0;
    tempGaps = new int[difference];
    finalTemps = new int[difference];
    for (int i = 0; i < difference; i++) {
        tempGaps[i] = temp[0] + i;
        if (tempGaps[i] == temp[j]) {
            finalTemps[i] = map.get(new Integer(tempGaps[i]));
            j++;
        } else {
            finalTemps[i] = 0;
        }
    }
}output: https://pastebin.com/nFCZXFyp

Output: 输出:

7 ->1 9 ->1 10 ->1 12 ->1 14 ->2 15 ->1 16 ->1 18 ->2 19 ->1 21 ->1 
TEMP GAPS
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 
FINAL TEMPS
1 0 1 1 0 1 0 2 0 0 0 0 0 0 0

My finalTemp output stops after 14 degrees - occurs 2 times. 我的finalTemp输出在14度后停止-发生2次。 It does this after any data set I put in which has a frequency of more than 1. Please help! 它会在我输入的任何频率大于1的数据集之后执行此操作。请帮助! Thanks!! 谢谢!!

I don't believe you need the j variable. 我认为您不需要j变量。 It seems to make things confusing, especially because the for loop is only a single pass-through. 这似乎使事情变得混乱,特别是因为for循环只是单个传递。 Instead, fetch the value from the map. 而是从映射中获取值。 If null, assign 0, otherwise, assign the value. 如果为null,则分配0,否则,分配值。

public void fillGaps() {       
    tempGaps = new int[difference];
    finalTemps = new int[difference];
    for (int i = 0; i < difference; i++) { //navigate through every temperature
        tempGaps[i] = temp[0] + i; //assign the current temperature
        Integer frequency = map.get(new Integer(tempGaps[i])); //fetch the frequency
        finalTemps[i] = frequency == null ? 0 : frequency; //assign 0 if null, otherwise frequency if not null
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM