I am trying to develop a simple client-server application to send a command to the server, process it, then send the result back and display it.
The user will be asked to enter a request in the form of "command xy".
For example, the user will enter: add 5 10
The output will then be The add result is: 30
The application can accept the following as command: add, subtract, multiply, divide
As the user is expected to input the request in one line, I am thinking of storing the user input in an array and use a switch-case such that if the first command is add, it will add the x and y. If the first command is substract, it will minus the x and y...
However, in the user request, there is a combination of string (the command) and integers (x and y). I am unsure how to do this. Also, is my approach efficient?
I already figured out the connection set up for client and server.
You may use a Scanner
and parse the line with the user input using Scanner's next
, nextInt
methods:
String userInput = "add 5 10";
Scanner scan = new Scanner(userInput);
String cmd = scan.next();
int arg1 = scan.nextInt();
int arg2 = scan.nextInt();
int res = switch (cmd) {
case "add" -> arg1 + arg2;
case "subtract" -> arg1 - arg2;
default -> throw new IllegalArgumentException("Unsupported command: " + cmd);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.