このプログラムでは、サーバーはクライアントから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);
}
}
}