gpt4 book ai didi

java - 无法从读取标准输入流的方法返回 main()

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

我基本上试图从从标准输入流读取用户输入的方法返回。由于用户可以选择退出应用程序,因此我试图找出执行此操作的最佳方法exit 。理想情况下,我将能够从 begin() 返回并让 main() 完成,从而退出应用程序。

public static void main(String[] args) {
begin();
}

private static void begin(){
Machine aMachine = new Machine();
String select=null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
try {
select = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your selection");
return;
}catch(Exception ex){
System.out.println("Error trying to evaluate your input");
return;
}

if (Pattern.matches("[RQrq1-6]", select)) {
aMachine.getCommand(select.toUpperCase()).execute(aMachine);
}
else {
System.out.println(aMachine.badCommand()+select);
aMachine.getStatus();
}
}
}

aMachine使用以下方法执行用户给定的命令时,就会发生主要逻辑:

aMachine.getCommand(select.toUpperCase()).execute(aMachine);

同样,问题是用户输入命令 Q 或 q 后如何退出应用程序。退出命令如下:

public class CommandQuit implements Command {

public void execute(Machine aMachine) {
aMachine.getStatus();
return; //I would expect this to force begin() to exit and give control back to main()
}
}

现在遵循我之前的建议 question ,要退出应用程序,我尝试返回 main() 并基本上让 main() 完成。这样我就可以避免使用 System.exit(0),尽管这样也可以。

因此,在这个示例中,我在 CommandQuit 类的 execute 方法中有一个 return 语句,当我们收到一个Q,或来自用户的 q。但是,当 begin() 执行退出命令时,不是从 while(true) 循环返回,而是退出 begin(),并且回到 main(),控制流似乎永远不会响应 CommandQuit 的 execute 方法中的 return;

我的示例中是否缺少任何内容?也许有些事情太明显了,以至于我现在看不到它。感谢您的帮助。

最佳答案

execute() 中的 return 语句从 execute() 返回,而不是 begin()。通常在这些情况下,CommandQuit.execute()aMachine 上设置一个标志,然后 begin() 检查 aMachine 顶部的标志。循环:

while (aMachine.stillRunning()) {  // instead of while (true)
...
// This will clear aMachine.stillRunning() if the user quits.
aMachine.getCommand(select.toUpperCase()).execute(aMachine);
}

关于java - 无法从读取标准输入流的方法返回 main(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1736450/

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