无法从 for (int i) 循环中找到 i 上的符号

Cannot find symbol on i from for (int i) loop

我正在尝试获取 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。这是为什么?有人可以帮忙吗?

嘿,使用数组索引无法访问 cookie,这是访问的唯一方法,请在此处输入代码

 Cookie[] cookies = request.getCookies();

String userId = null;
for(Cookie cookie : cookies)
{
    if("uid".equals(cookie.getName()))
{
        userId = cookie.getValue();
    }
}
Cookie[] cs = request.getCookies();
for(Cookie c: cs) {
    System.out.println(c.getName() + "  " + c.getValue());
    c.setValue(c.getValue() + " added Value");
    response.addCookie(c);
}

这可能会有所帮助。

你的 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) 中的条件将始终涵盖这一点,因为 I 开始等于 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]);
}