简体   繁体   English

为什么我的变量没有在循环中更改?

[英]Why aren't my variables being altered in my loops?

I've got a method that is meant to work out the group of elements of a 3D array with the highest combined value. 我有一种方法可以计算出具有最高组合值的3D阵列的元素组。 I've got 3 nested loops that I'm using to go through my array, and as certain conditions are met I want to alter the variables. 我已经使用了3个嵌套循环来遍历数组,并且当满足某些条件时,我想更改变量。 However none of the variables are being used. 但是,没有使用任何变量。 I ant to alter int y and int m to whatever iteration of the for loop it's on if sum exceeds total . 如果sum超过total我希望将int yint m更改为for循环的任何迭代。

Thanks. 谢谢。 Here is my code: 这是我的代码:

    public void wettestMonth(){
        double sum = 0;
        double total = 0;
        int y = 0;
        int m = 0;

        //cycle through each year and month
        for(int i = 0; i < 34; i++){
            for(int j = 0; j < 12; j++){
                //reset the current month to 0 after each month has been cycled through
                sum = 0;
                for(int k = 0; k < 31; k++){
                    //only add the record if the current entry is not null (-99.99)
                    if(sortedData[i][j][k] != -99.99){
                        sum += sortedData[i][j][k];
                    }
                    //if the current month is wetter than the wettest one, make the current month the new wettest one
                    if(sum > total){
                        total = sum;
                        y = i;
                        m = j;
                    }
                }
            }
        }

        JOptionPane.showMessageDialog(null, "The wettest month on record was " +m +y, "Wettest Month.", JOptionPane.PLAIN_MESSAGE);

    }

Edit, I just reconstructed it with while loops instead and I'm getting an out-of-bounds error on what appears to be the problem line, if(sortedData[i][j][k] != -99.99) 编辑,我只是​​用while循环来重建它,而在似乎是问题行的if(sortedData[i][j][k] != -99.99)上出现了界外错误。

Edit 2, here is where I declare and initialise sortedData[][][] 编辑2,这是我声明和初始化sortedData[][][]

public class GetData { 公共类GetData {

//initialises an array that holds 34 years, each with 12 months, each of which has 31 entries for reach day
public double[][][] sortedData = new double[34][12][31];

//initialises a new scanner named rainFile
private Scanner rainFile;

//method for opening the file
public void openFile() {

    try{
        //as the input for the scanner we use the rainfall file
        rainFile = new Scanner(new File("C:\\\\Users\\\\admin\\\\Documents\\\\NetBeansProjects\\\\110_term3\\\\WeatherDataFiles\\\\rainfall.txt"));
    }
    catch(Exception e){
        //if no file has been found a JOptionPane will display an error message telling the user to double-check the file path
        JOptionPane.showMessageDialog(null, "Check the file path is correct.", "No file found!", JOptionPane.ERROR_MESSAGE);
    }
}

//method for reading the file
public void readFile(){

    //ignore the first 3 lines in the data file
    String dump1 = rainFile.nextLine();
    String dump2 = rainFile.nextLine();
    String dump3 = rainFile.nextLine();

        //these nested for loops will dictate the current index of sortedData
        for(int i = 0; i < 34; i++){
            for(int j = 0; j < 12; j++){

                //ignores the year and month at the start of each line
                String dump4 = rainFile.next();
                String dump5 = rainFile.next();

                //this final nested for loop dictates the final index of sortedData
                for(int k = 0; k < 31; k++){

                    //asigns the current value of scanner rainFile to String a
                    String a = rainFile.next();

                    //converts the String a to a double type and then assigns it to the current index of sortedData
                    double dbl = Double.parseDouble(a);
                    sortedData[i][j][k] = dbl;
                }

            }
        }

    }

Have you tried printing out the sum for each month? 您是否尝试过打印每个月的金额?

The most obvious possibility is that your sums are always less than 0 because of a buggy equality check. 最明显的可能性是,由于存在错误的相等性检查,您的总和始终小于0。

For this line, 对于这条线,

sortedData[i][j][k] != -99.99

It will be true unless the value is exactly what -99.99 rounds to. 除非该值正好是-99.99的四舍五入,否则将是真实的。 This may be unintended. 这可能是意外的。 For example, if you are constructing the value through floating point math somehow, you most likely won't get exactly the same value due to rounding errors. 例如,如果您以某种方式通过浮点数学构造该值,则由于舍入误差,您很可能不会获得完全相同的值。 Furthermore, use of a weird sentinel value like this is error prone and less readable. 此外,像这样使用一个奇怪的哨兵值容易出错并且可读性较差。 You're better off using an obvious sentinel value like NaN if you can. 如果可以的话,最好使用明显的哨兵值,例如NaN。

To see the problem, consider what would happen if your values are slightly different. 要查看该问题,请考虑如果您的值稍有不同会发生什么。 Say, -99.99000001. 说,-99.99000001。 Then after the first day, you already have a negative value. 在第一天之后,您已经有了一个负值。 After a month, the sum will be approximately -3099.69000031, much less than 0. Since the sum is always negative, it is never better than the original total 0, so the best never gets updated. 一个月后,总和约为-3099.69000031,远小于0。由于总和始终为负,因此它永远不会比原始总和0好,因此最好的总和将永远不会更新。

You probably also want to move the update check outside of the day loop. 您可能还希望将更新检查移到日循环之外。 This part looks like it's supposed to use the sum for the whole month, but you are running it with the partial sum of every day of the month. 这部分看起来应该使用整个月的总和,但是您使用当月的每一天的部分总和来运行它。 It won't actually cause incorrect results as long as the values being added are nonnegative (but they probably aren't due to the aforementioned bug), but you should still fix it. 只要添加的值是非负数,它实际上不会导致不正确的结果(但它们可能不是由于上述错误引起的),但是您仍然应该修复它。

                if(sum > total){
                    total = sum;
                    y = i;
                    m = j;
                }

I don't see anything wrong on your code. 我看不到您的代码有任何问题。

Maybe the following condition never evals to true? 也许以下条件永远不会成立?

if(sortedData[i][j][k] != -99.99)

Carefully, reviewed the first code snippet that has been provided, it appears to me that you have been doing if check for the size inside the for loop, moved the for loop vars to the finals, added some further comments. 仔细地检查了提供的第一个代码段,对我来说,您似乎一直在检查for循环内的大小,将for循环vars移到了finals,并添加了一些其他注释。

You could try and run your swing app through the Eclipse debug and see what results you get at each line in your application ? 您可以尝试通过Eclipse调试运行swing应用程序,并查看在应用程序的每一行得到的结果是什么?

Would expect it to work given correct input 3D array)) 在正确输入3D阵列的情况下,它可以正常工作))

/**
* This method calculates the wettest month during the certain period of time.
*/
public void wettestMonth(){
    double sum = 0;
    double total = 0;
    int y = 0;
    int m = 0;
    final int numberOfYearsToCycleThrough = 34;
    final int numberOfMonthsToCycleThrough = 12;
    //cycle through each year and month
    for (int i = 0; i < numberOfYearsToCycleThrough; i++) {
        for (int j = 0; j < numberOfMonthsToCycleThrough; j++) {
            sum = 0;
            for (int k = 0; k < 31; k++){
                //only add the record if the current entry is not null (-99.99)
                if (sortedData[i][j][k] != null && sortedData[i][j][k] != -99.99) {
                   sum += sortedData[i][j][k];
                }
            }
        //if the current month is wetter than the wettest one, make the current month the new wettest one
             if (sum > total) {
                total = sum;
                y = i;
                m = j;
             }
         }
     }
     JOptionPane.showMessageDialog(null, "The wettest month on record was " +m +y, "Wettest Month.", JOptionPane.PLAIN_MESSAGE);
}

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

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