首页 > 解决方案 > 变量仅在 while 循环内失去价值

问题描述

我正在尝试在 excel 中比较来自 2 个不同电子表格的数据。当我这样做时,我将某些单元格的值存储在检查变量(userCheck、、sessionCheckidCheck)中。我发现在第一次检查和第二次检查之间它们具有不同的值,这意味着在嵌套的 while 循环之前/期间,Check 变量具有它们启动时使用的值,但在嵌套的 while 循环之后,它们具有在嵌套 while 循环之前的 if 语句中定义的值。

我不明白为什么值在嵌套 while 循环中基本上没有改变。

爪哇

String userCheck = "x";
int sessionCheck = -1;
int idCheck = -1;
double[] predict;
predict = new double[13];

rows.next();
rows2.next();
while(rows.hasNext()) {
    Row row = rows.next();
    Cell msg = row.getCell(49);
    Cell id = row.getCell(64);
    Cell user = row.getCell(0);
    Cell session = row.getCell(1);
    if(msg != null) {

        if(msg.getStringCellValue().charAt(0)!='<'
          &&msg.getStringCellValue().charAt(1)!='k'
          &&!msg.getStringCellValue().substring(0,7).equals("Awesome")) {
            idCheck = (int)id.getNumericCellValue();
            userCheck = user.getStringCellValue();
            sessionCheck = (int)session.getNumericCellValue();
        }


        while(rows2.hasNext()) {
            Row row2 = rows2.next();
            Cell user2 = row2.getCell(0);
            Cell session2 = row2.getCell(1);
            Cell id2 = row2.getCell(2);
            //First Check
            System.out.println(userCheck);

            if(user2.getStringCellValue().equals(userCheck)) {

                if((int)session2.getNumericCellValue() == sessionCheck) {

                    if((int)id2.getNumericCellValue() == idCheck) {

                        for(int i=0;i<13;i++) {
                            predict[i] = 
 double)row2.getCell(i+2).getNumericCellValue();
                        }
                    }
                }
            }

        }
        //Second Check
        System.out.println(userCheck);

//code and brackets continue on below but i figured this block should be enough

标签: javalocal-variables

解决方案


我没有足够的声誉发表评论,所以我将其发布为答案:

我认为您的 while 循环旨在执行以下操作(伪代码):

for all row1 in rows
  for all row2 in rows2
    compare row1 with row2

例如,您想将rows 中的每一行与rows2 中的每一行进行比较?(如果没有,请不要进一步阅读。我当时没有得到它。)

但是,您不使用for each循环,而是使用迭代器。并且您在两个 while 循环之前启动它们。这意味着,您按预期进入外while循环,然后也按预期进入内while循环。rows2.hasNext() == false然后内部 while 循环也按预期遍历 rows2 的所有行(直到)。但是当外部 while 循环第二次面对内部循环时,不会重置 rows2 的迭代器。所以rows2.hasNext() == false仍然成立,并且永远不会再次进入内循环。


推荐阅读