Java 嵌套方法中的while循环后无法返回值
我在添加第二个while循环后返回DVDs对象时遇到问题。此函数在添加while循环之前工作得非常好。编译期间出错-找不到符号:变量currentDVDJava 嵌套方法中的while循环后无法返回值,java,nested,return,Java,Nested,Return,我在添加第二个while循环后返回DVDs对象时遇到问题。此函数在添加while循环之前工作得非常好。编译期间出错-找不到符号:变量currentDVD public DVDs getNewDVDInfo() { boolean keepRunning = true; boolean promptAddAgain = true; while (keepRunning) { String title = input.readString("Please en
public DVDs getNewDVDInfo() {
boolean keepRunning = true;
boolean promptAddAgain = true;
while (keepRunning) {
String title = input.readString("Please enter the move title.");
String releaseDate = input.readString("Please enter the release date.");
String MPAArating = input.readString("Please enter the MPAA rating.");
String directorName = input.readString("Please enter the director name.");
String studio = input.readString("Please enter the name of the studio.");
String userRating = input.readString("Please type in any comment you would "
+ "like to leave for this movie below.");
DVDs currentDVD = new DVDs(releaseDate, MPAArating, directorName, studio, userRating);
currentDVD.setTitle(title);
while (promptAddAgain) {
String userAns = input.readString("Would you like to add another DVD to the library?");
if (userAns.equals("n")) {
input.print("Thank you. Returning to main menu.");
keepRunning = false;
promptAddAgain = false;
} else if (userAns.equals("y")) {
input.print("\n");
} else {
input.print("Unknown input, please try again.");
keepRunning = false;
}
}
}
return currentDVD; //<--- error
}
出现错误的原因是currentDVD当前是在外部while循环内定义的,但在它超出范围后,您在该循环外引用它。解决此问题的一种方法是在第一个while循环之前声明currentDVD:
请记住,使用上述方法,您的getNewDVDInfo方法可能会返回null,因此调用者应该知道这一点。解决了这个问题。没有注意到那里的范围。谢谢当然,就是这样;
DVDs currentDVD = null;
while (keepRunning) {
...
}
return currentDVD;