我正在尝试获取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/