gpt4 book ai didi

java - 在方法内嵌套 while 循环后无法返回值

转载 作者:行者123 更新时间:2023-12-01 08:55:42 25 4
gpt4 key购买 nike

添加第二个 while 循环(promptAddAgain)后,我在返回 DVD 对象时遇到问题。在添加 while 循环之前,该函数可以完美运行。编译期间出错 - 找不到符号:变量 currentDVD。

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:

DVDs currentDVD = null;
while (keepRunning) {
...
}
return currentDVD;

请记住,使用上述方法时,您的 getNewDVDInfo() 方法可能会返回 null,因此调用者应该意识到这一点。

关于java - 在方法内嵌套 while 循环后无法返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42048799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com