在数组中查找下一个double值

时间:2014-01-14 17:09:47

标签: java

我正在编写一个无线电调谐器的模拟。现在我想要一个可以循环通过数组或arraylist的方法,步长为0.05MHz。目前,我有一个带有我最喜欢的无线电频率的阵列,如果找到频率,则必须停止循环。

public static double favFrequencies [] = {89.8, 91.5, 93.7, 95.1, 97.7, 99.2, 100.7, 101.2, 101.7, 102.7, 103.0, 104.4};

目前我有以下代码:

public static void searchDown()
{
    double startFrequency = Math.round(currentFreq * 100);
    double maxFrequency = Math.round(87.80 * 100);
    for (double f = startFrequency; f > maxFrequency; f -= 5) {
        //boolean nextFavFound = false;
        if (f < 8785)
        {
            f = 10800;
        }
        for (double f2 : favFrequencies) {
            if (f / 100 == f2) {
                nextFavFound = true;
                //break;
            }
        }
        if (nextFavFound) {
            currentFreq = f /100;
            RadioGUI.lblFreq.setText("FM " + Double.toString(currentFreq)+ "Mhz");
            System.out.println("next favFrequency: " + f / 100);
            nextFavFound = false;
            break;
        }
    }
}

它确实工作得很好,但是当我再次运行该方法时,它将无法使用第一次的新输出值。

3 个答案:

答案 0 :(得分:1)

使用for - 循环和带小数位的double增量时,您将遇到精度问题。对你的问题采取一种务实的方法是乘以100倍。

public static void main(String[] args) {
    double startFrequency = Math.round(88 * 100);
    double maxFrequency = Math.round(108 * 100);
    for (double f = startFrequency; f < maxFrequency; f += 5) {
        boolean nextFavFound = false;
        for (double f2 : favFrequencies) {
            if (f / 100 == f2) {
                nextFavFound = true;
                break;
            }
        }
        if (nextFavFound) {
            System.out.println("next favFrequency: " + f / 100);
        }
    }
}

答案 1 :(得分:0)

从一个简单的for loop开始,以最小频率为基础启动i,停在最大频率并增加0.05(确保我是一个双倍)。然后,您可以检查每一步:

boolean containsFav = false;
for(double i=80.00;i<110.00;i=i+0.05){
    if(Arrays.asList(favFrequencies).contains(i)){
        containsFav = true;
        break;
    }
}

答案 2 :(得分:0)

使用以下代码我解决了我的问题。

public static void searchUp()
{
    currentFreq +=0.05;
    double startFrequency = Math.round(currentFreq * 100);
    double maxFrequency = Math.round(108 * 100);
    for (double f = startFrequency; f < maxFrequency; f += 5) {
        //boolean nextFavFound = false;
        if (f > 10790)
        {
            f = 8780;
        }
        for (double f2 : favFrequencies) {
            if (f / 100 == f2) {
                nextFavFound = true;
                //break;
            }
        }
        if (nextFavFound) {
            currentFreq = f /100;
            RadioGUI.lblFreq.setText("FM " + Double.toString(currentFreq)+ "Mhz");
            //System.out.println("next favFrequency: " + f / 100);
            nextFavFound = false;
            //currentFreq +=0.05;
            break;
        }
    }
}