JAVA IF ELSE语句导致我的代码出错

-1 java compiler-errors cannot-find-symbol

        Part part = request.getPart("file");
        if (part != null){
        String fileName = extractFileName(part);
        String filePath = savePath + File.separator + fileName;
        part.write(savePath + File.separator + fileName);
        String imageName = fileName;
        } else{
            String fileName = "avatar.jpg";
            String filePath = savePath + File.separator + fileName;
            part.write(savePath + File.separator + fileName);
            String imageName = fileName;
        }
Run Code Online (Sandbox Code Playgroud)

在将if else语句插入代码后,我底部的代码收到此错误说:imageName无法解析为变量,filePath无法解析为变量.但是,一旦我评论了我的if else声明,一切都很好.有人能告诉我哪里出错了吗?

        request.setAttribute("Pic", filePath);
        request.setAttribute("PicName", imageName);
Run Code Online (Sandbox Code Playgroud)

小智 5

您的"filePath"和"imageName"变量仅在if或else块中可见.在if/then块之前声明这些变量,然后在if/then代码中设置变量,而不是重新声明它.

String filePath = "";
String imageName = "";
if (...) {
...
} else {
...
}
request.setAttribute("Pic", filePath);
request.setAttribute("PicName", imageName);
Run Code Online (Sandbox Code Playgroud)

有关范围的更多信息,请参见http://www.java-made-easy.com/variable-scope.html.