我试图制作一个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);


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

String期望Scanner时输入int将引发InputMismatchException;您需要处理它。

10-08 19:37