2015-12-12 78 views
1

我想製作一個Java遠程控制程序,通過客戶端訪問它,這是來自服務器的一些代碼。我是編程新手,我想要一些幫助。 我希望我的服務器繼續運行 - >問題是,當我爲CmdMenuDecision分配字符串值時,服務器崩潰。任何方式呢? 我也得到內存泄漏,在詮釋CmdMenuDecision =新掃描儀(System.in).nextInt(); ,,我使用@SuppressWarnings(「資源」),我不確定它是否好。如何保持在錯誤期間運行的Java程序

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

回答

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

這將確保您得到了CmdMenuDecision變量的Integer輸入。

輸入一個StringScanner期待一個int將引發InputMismatchException時;你需要處理它。

+1

工作,謝謝。 –