java - 无法通过for(int i)循环在i上找到符号

标签 java for-loop compiler-errors cannot-find-symbol

我正在尝试获取Cookie列表,并通过将一个新String串联起来来更改其值。这是我的代码:

    String color = request.getParameter("color");
    Cookie cookies[] = request.getCookies(); // get client's cookies;
    String cn;
    String cv;

    if ( cookies.length != 0 ) { 
        // get the name of each cookie
        for ( int i = 0; i < cookies.length; i++ ) 
            cn = cookies[ i ].getName();
            cv = cookies[ i ].getValue();
            cv = cv.concat(color);
            cookies[i].setValue(cv);
            response.addCookie(cookies[i]);

我在cn = cookies[ i ].getName();上收到错误错误是cannot find symbol,它指示i。这是为什么?有人可以帮忙吗?

最佳答案

您的for循环没有大括号。这意味着只有for循环定义下方的第一行实际上是循环的一部分。结果,后续行引用了一个变量i,该变量在其作用域内不存在(因为它仅存在于for循环的作用域内)。

例如,在此示例中,仅当someValue == 123.时才调用第一个打印方法。但是,第二个打印方法将始终被调用,因为它不在if语句中:

if(someValue == 123)
    System.out.println("This number equals 123");
    System.out.println("This number is greater than 122");

但是,在此示例中,两个调用都在if语句内,因此,如果someValue == 123:,则两个调用都将被调用,只有
if(someValue == 123){
    System.out.println("This number equals 123");
    System.out.println("This number is greater than 122");
}

另外,不需要if(cookies.length != 0),因为for循环(i < cookies.length)中的条件将始终覆盖此条件,因为我开始等于0。

尝试这个:
for(int i = 0; i < cookies.length; i++){
    cn = cookies[ i ].getName();
    cv = cookies[ i ].getValue();
    cv = cv.concat(color);
    cookies[i].setValue(cv);
    response.addCookie(cookies[i]);
}

关于java - 无法通过for(int i)循环在i上找到符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33901377/

相关文章:

java - 如何更新显示更新对象属性的 JAVA FX 元素(标签、列表等)

c - 我正在做一个混合 2 个单词的(字符串)函数,但程序根本不工作

c - 关于C循环的问题

java - 可以检测 Java 应用程序中的系统代理设置,但不能检测 JUnit

java - Java HashMap使用通配符嵌套泛型

python - 错误 : invalid mode ('r' ) - Cannot conduct Cognate Analysis using LingPy in Python 2. 7

java - Maven 多模块项目打破编译时类解析

c++ - 我的以下代码有错误

java - 不兼容的类型 : inference variable T has incompatible bounds equality constraints: capture#1 of ? 扩展了 java.lang.Object

python - 我如何释放由 "for"引起的内存