简体   繁体   English

将 String 和 Int 存储在数组中作为 Java 中的输入

[英]Store String and Int in an Array as input in Java

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".将要求用户以“命令 xy”的形式输入请求。

For example, the user will enter: add 5 10例如,用户将输入: add 5 10
The output will then be The add result is: 30然后 output 将是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.由于希望用户在一行中输入请求,我正在考虑将用户输入存储在一个数组中并使用一个 switch-case,这样如果第一个命令是 add,它将添加 x 和 y。 If the first command is substract, it will minus the x and y...如果第一个命令是减法,它将减去 x 和 y...

However, in the user request, there is a combination of string (the command) and integers (x and y).但是,在用户请求中,存在字符串(命令)和整数(x 和 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:您可以使用Scanner并使用 Scanner 的nextnextInt方法解析用户输入的行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM