Java 无法解析变量ArrayList
我做错了什么?有人能帮忙吗? 在“if(result.get(0)…”,它说“结果无法解析。” 我被困在这上面了Java 无法解析变量ArrayList,java,html,jsp,arraylist,Java,Html,Jsp,Arraylist,我做错了什么?有人能帮忙吗? 在“if(result.get(0)…”,它说“结果无法解析。” 我被困在这上面了 <% if(session != null){ ArrayList<Prize> result = new ArrayList<Prize>(); result = (ArrayList<Prize>) session.getAttribute("result"); } %> <
<%
if(session != null){
ArrayList<Prize> result = new ArrayList<Prize>();
result = (ArrayList<Prize>) session.getAttribute("result");
}
%>
<%
if(result.get(0).getIdPrize() != null){
prize = result.get(0);
out.println(prize.getLottery(prize.getIdLottery()) +
" - " + prize.getHour(prize.getIdHour()) +
" - " + prize.getDate(prize.getDatePrize()));
}
%>
变量结果在第一个if块中声明,之后不再可见 试试看
<%
ArrayList<Prize> result = new ArrayList<Prize>();
if(session != null){
result = (ArrayList<Prize>) session.getAttribute("result");
}
%>
<%
if(result.size() > 0 && result.get(0).getIdPrize() != null){
prize = result.get(0);
out.println(prize.getLottery(prize.getIdLottery()) +
" - " + prize.getHour(prize.getIdHour()) +
" - " + prize.getDate(prize.getDatePrize()));
}
%>
0&&result.get(0.getIdrize()!=空){
奖品=结果。获得(0);
out.println(prize.getlotting(prize.getIdLottery())+
“-”+prize.getHour(prize.getIdHour())+
“-”+prize.getDate(prize.getDatePrize());
}
%>
正如@Vyncent所说,将结果声明移到if结构之外。一个常见的新视图错误是不知道变量的范围。
括号中的内容将是变量的生命周期
{
int a = 3; // You can use this variable inside this brackets
System.out.println(a);
}
System.out.println(a); => Java Compiler will throw an error.
这适用于所有if/while/for语句。
所以对于解决方案,只需知道如何使用变量的范围
ArrayList<Prize> result = new ArrayList<Prize>();
if(session != null){
result = (ArrayList<Prize>) session.getAttribute("result");
}
if(result.get(0).getIdPrize() != null){
prize = result.get(0);
out.println(prize.getLottery(prize.getIdLottery()) +
" - " + prize.getHour(prize.getIdHour()) +
" - " + prize.getDate(prize.getDatePrize()));
}
ArrayList结果=新建ArrayList();
if(会话!=null){
结果=(ArrayList)session.getAttribute(“结果”);
}
if(result.get(0).getIdPrize()!=null){
奖品=结果。获得(0);
out.println(prize.getlotting(prize.getIdLottery())+
“-”+prize.getHour(prize.getIdHour())+
“-”+prize.getDate(prize.getDatePrize());
}
result在if语句中声明,在if语句之后不再可见。您可以将第二个if语句移动到第一个if语句中,使其正常工作。可能是最简单的修复方法。如果我在错误之外声明结果,则继续…移动第二个if也会继续错误。并且在其上方的强制转换警告“unchecked cast”