Reputation: 75
I am trying to make a java remote control progam, accesing it via a client, this is some code from the server. I am new to programming, and i would like some help. I want my server to keep running -> problem is, that when i assign a string value to CmdMenuDecision , the server crashes. Any way around it? I also get memory leak at ,, int CmdMenuDecision = new Scanner(System.in).nextInt(); ,, , i use @SuppressWarnings("resource") and i'm not sure if it's good or not.
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();
}
}
}
Upvotes: 1
Views: 92
Reputation: 17132
Change
int CmdMenuDecision = new Scanner(System.in).nextInt();
to
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);
This will make sure that you get an Integer
input for the CmdMenuDecision
variable.
Entering a String
when the Scanner
is expecting an int
will throw an InputMismatchException; you need to handle it.
Upvotes: 1