gpt4 book ai didi

Java 服务器基本计算器

转载 作者:行者123 更新时间:2023-12-01 14:53:18 26 4
gpt4 key购买 nike

在此程序中,我的服务器从客户端获取一个命令,后跟 1 或 2 个操作数,并返回操作结果。

我在扫描客户端输入行和在 switch 语句中执行实际操作时遇到困难,如果有人能指出我正确的方向,我将不胜感激。

代码如下:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

// Takes in a mathematical operation and the operands from a client and returns the result
// Valid operations are add, sub, multiply, power, divide, remainder, square
public class MathServer
{
public static void main(String [] args) throws IOException
{
ServerSocket yourSock = new ServerSocket(50000); //put server online
while(true)
{
System.out.println("Waiting to accept connection");
Socket clientSock = yourSock.accept(); //open server to connections
System.out.println("Connection accepted");
process(clientSock); //process accepted connection
System.out.println("Connection closed");
}
}

//BufferedReader(Reader r)
static void process(Socket sock) throws IOException
{
InputStream in = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
OutputStream out = sock.getOutputStream();
PrintWriter pw = new PrintWriter(out, true);

String input = br.readLine(); //get user input from client

while(input != null && !input.equals("bye")) //check for input, if bye exit connection
{
int answer = operate(input); //perform desired operation on user input
pw.println(answer); //print out result
input = br.readLine(); //get next line of input
}
sock.close();
}

//Talk to the client
static int operate(String s)
{
System.out.println(s); //check if same as client input

Scanner myScanner = new Scanner(s);
String opType = myScanner.next(); //gets desired operation

System.out.println(opType); //checks for correct operation

switch (opType) {
case "add":
return (myScanner.nextInt() + myScanner.nextInt());
case "sub":
return (myScanner.nextInt() - myScanner.nextInt());
case "multiply":
return (myScanner.nextInt() * myScanner.nextInt());
case "power":
return (int) Math.pow(myScanner.nextInt(), myScanner.nextInt());
case "divide":
return myScanner.nextInt() / myScanner.nextInt();
case "remainder":
return myScanner.nextInt() % myScanner.nextInt();
case "square":
return (int) Math.pow(myScanner.nextInt(), 2);
default:
return (int) Math.pow(myScanner.nextInt(), 3);
}
}
}

最佳答案

当您在服务器中使用 BufferedReade.readLine() 进行读取时,请确保从客户端发送换行符(常见错误)。此外,您可能需要从客户端刷新 OutputStream。由于您的 Scanner 读取变量的方式,您需要从客户端在一行中发送值,例如

add 100 200

关于Java 服务器基本计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14594941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com