gpt4 book ai didi

java - java程序出错时如何保持运行

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:01 24 4
gpt4 key购买 nike

我正在尝试制作一个java远程控制程序,通过客户端访问它,这是来自服务器的一些代码。我是编程新手,我需要一些帮助。 我希望我的服务器继续运行 -> 问题是,当我向 CmdMenuDecision 分配字符串值时,服务器崩溃。有办法解决吗? 我还在 ,, int CmdMenuDecision = new Scanner(System.in).nextInt(); 处遇到内存泄漏,,,我使用@SuppressWarnings("resource"),我不确定它是否好。

private static Scanner SCANNER = new Scanner(System. in );
private String command1;
private String command2;
private String command3;
private String command4;

public void runtimeChoice() {
System.out.println("what do you want to do? 1. Execute CMD Command");
int CmdMenuDecision = new Scanner(System. in ).nextInt();
switch (CmdMenuDecision) {
case 1:
CMDCommand();
break;
default:
System.out.println("No valid answer");
break;
}
private void CMDCommand() {
System.out.println("CMD is working!");
Runtime rt = Runtime.getRuntime();
try {
System.out.println("Insert desired command");
command1 = CmdCommand.nextLine();
command2 = CmdCommand.nextLine();
command3 = CmdCommand.nextLine();
command4 = CmdCommand.nextLine();
rt.exec(new String[] {
"cmd.exe", "/c", /*"start",*/
command1, command2, command3, command4
});
System.out.println("Command: " + command1 + " " + command2 + " " + command3 + " " + command4 + " executed succesfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

改变

int CmdMenuDecision = new Scanner(System.in).nextInt();

boolean flag = false;

do {
try {
int CmdMenuDecision = new Scanner(System.in).nextInt();
flag = true; // If the execution flow reached this line then that means that the user input was correct; break the loop.
}
catch(InputMismatchException e) {
System.out.println("Invalid input, try again.");
}
}while(!flag);

这将确保您获得 CmdMenuDecision 变量的 Integer 输入。

扫描器期望int输入String时,将抛出InputMismatchException;你需要处理它。

关于java - java程序出错时如何保持运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245770/

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