如何在错误

时间:2015-12-12 22:30:46

标签: java

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

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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

更改

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);

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

String期待Scanner时输入int会抛出 InputMismatchException ;你需要处理它。