我正在创建一个包含String和Integer变量的变量表单。
即我从page1.jsp页面获取的参数是name1,place1,country1,name2,place2,country2,name3,place3,country3。
我想获取这些变量并在page2.jsp上打印。
这是我到目前为止所尝试过的。
for(i=1;i>=3;i++)
{
String name(i) = request.getParameter("name"+i);
String place(i) = request.getParameter("place"+i);
String country(i) = request.getParameter("country"+i);
}
for(i=1;i>=3;i++)
{
out.println(name(i));
out.println(place(i));
out.println(country(i));
}
我得到的错误是:
Syntax error, insert ";" to complete BlockStatements
6: int i;
7: for(i=1;i>=j;i++)
8: {
9: String name(i) = request.getParameter("name"+i);
10: String place(i) = request.getParameter("place"+i);
11: String country(i) = request.getParameter("country"+i);
12: }
An error occurred at line: 9 in the jsp file: /page2.jsp Type mismatch: cannot convert from String to int
An error occurred at line: 10 in the jsp file: /page2.jsp
Syntax error, insert ";" to complete LocalVariableDeclarationStatement
答案 0 :(得分:0)
您没有使用数组
尝试这样做
String[] name = new String[3];
String[] place = new String[3];
String[] country = new String[3];
for(int i=0;i<3;i++)
{
name[i]= request.getParameter("name"+i);
place[i] = request.getParameter("place"+i);
country[i] = request.getParameter("country"+i);
}
for(int i=0;i<3;i++)
{
out.println(name[i]);
out.println(place[i]);
out.println(country[i]);
}
答案 1 :(得分:0)
我不知道您的上一页价值即将来临......
要存储在数组中,还有另一种方法
String[] name= request.getParameterValues("name");
String[] place= request.getParameterValues("place");
String[] country= request.getParameterValues("country");
for(int i=0;i<3;i++)
{
out.println(name[i]);
out.println(place[i]);
out.println(country[i]);
}
答案 2 :(得分:0)
我注意到你的循环中出现了错误的情况。
for(i=1;i>=3;i++) // this i>=3 will return false since i is not greater than or equal to 3.
将循环条件更改为小于或等于3.
for(i=1;i<=3;i++){
name[i]= request.getParameter("name"+i);
place[i] = request.getParameter("place"+i);
country[i] = request.getParameter("country"+i);
/*
it will access the ff.
"name1" to "name3"
"place1" to "place3"
"country1" to "country3"
*/
}
然后将您的数组大小声明更改为4,因为您在索引3上方进行访问。
String[] name = new String[4];
String[] place = new String[4];
String[] country = new String[4];
您还获得了java.lang.ArrayIndexOutOfBoundsException:
,因为您访问过非法索引。您的索引是负数或大于或等于数组的大小,因为它抛出ArrayIndexOutOfBoundsException,请确保您访问合法索引。
如果你有这样的东西,它将抛出一个ArrayIndexOutOfBoundsException,因为你访问相同大小的数组;
String[] name = new String[3];
out.println(name[3]); //you can only access 0 - 2 index, thats whay it throws ArrayIndexOutOfBoundsException,