有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java字符串数组:“从未使用在“i++”处更改的值”

这是我的密码:

String[] queries = new String[2];
int i = 0;
Boolean result;
queries[i++] = "<query 1>";
queries[i++] = "<query 2>"; //Warning shown here
result = dbOpenHelper.ExecuteMyTransaction(queries);

第二个i++突出显示,并显示警告“从未使用在'i++'处更改的值”。这段代码是由另一个人编写的,据我所知,这里<query 1><query 2>分别被分配给queries[1]queries[2],但是它必须显示一个错误,因为数组的大小是2。没有错误,这让我对这里发生的事情感到困惑。我是否可以安全地删除第二个赋值,或者将第一个赋值更改为queries[i]


共 (5) 个答案

  1. # 1 楼答案

    • but then it must show an error, as the array is of size 2.

    如果你尝试访问queries[2],你肯定会了解What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?。尽管你目前的代码不是这样

    • There's no error and this kind of confuses me on what's happening here.

    数组边界不会在编译时检查,而是在运行时检查,因为大小是在运行时分配的。更多关于Why isn't the ArrayIndexOutOfBoundsException a compile time error?的详细信息

    • Can I safely remove the second assignment, or change the first one to queries[i]?

    您可以删除该赋值,或如其他人所述,仅在第一个赋值中使用后增量运算符

    queries[i++] = "<query 1>"; // index accessed is 0 here
    queries[i] = "<query 2>"; // i=1 here
    
    • The value changed at 'i++' is never used'

    这是一个编译时警告,因为编译器希望您在处理其值的同一范围内对i进一步执行操作

  2. # 2 楼答案

    ++i increments i and then uses the variable. (Pre-increment)

    i++ uses and then increments the variable.(Post-increment)

    在代码中,这是增量后操作

    queries[i++] = "<query 1>"; // It's equivalent to queries[0] = "<query 1>";
    queries[i++] = "<query 2>"; // It's equivalent to queries[1] = "<query 2>";
    

    因此,您的代码应该可以正常工作。然而,将第二个查询用作queries[i] = "<query 2>";总是好的

  3. # 3 楼答案

    i++ means post increment, which means first the i value is taken and used, then is incremented.

    您的代码是正确的。您可以忽略此警告,并尝试在下面的代码中删除此警告

    String[] queries = new String[2];
    int i = 0;
    Boolean result;
    queries[i++] = "<query 1>";
    queries[i] = "<query 2>"; //change this here
    result = dbOpenHelper.ExecuteMyTransaction(queries);
    
  4. # 4 楼答案

    第二个i++也可以是i,因为i不再被检查。 后增量i++将返回当前值i,然后返回增量i

  5. # 5 楼答案

    代码是正确的,您可以安全地忽略此警告,或者将带下划线的i++替换为i

    这个警告只是表明,由于在该范围内没有进一步使用i变量,所以增加其值或不增加其值都没有效果,而且毫无意义