JAVA客户机服务器读取带有新行的字符串

JAVA客户机服务器读取带有新行的字符串,java,client-server,bufferedreader,printwriter,Java,Client Server,Bufferedreader,Printwriter,我正在写一个带有客户端和服务器的小程序。服务器程序中包含计算器程序。当服务器和客户机运行时,客户机可以输入等式2+2,服务器将计算它并将答案发送给客户机。程序还应该包含一个帮助选项,因此当命令帮助从客户端发送到服务器时,服务器应该返回一个帮助菜单。 我的问题是,它返回帮助菜单,但都在一行中,它不是打印出来的控制台在单独的行。谢谢你的帮助 服务器代码: package One; import java.io.*; import java.net.*; public c

我正在写一个带有客户端和服务器的小程序。服务器程序中包含计算器程序。当服务器和客户机运行时,客户机可以输入等式2+2,服务器将计算它并将答案发送给客户机。程序还应该包含一个帮助选项,因此当命令帮助从客户端发送到服务器时,服务器应该返回一个帮助菜单。 我的问题是,它返回帮助菜单,但都在一行中,它不是打印出来的控制台在单独的行。谢谢你的帮助

服务器代码:

package One;

    import java.io.*;
    import java.net.*;


    public class ServerCalculator {

        static double answer;

        public ServerCalculator(){

            System.out.println("Server...");

            theServer();

            }
        void theServer(){

            try{

                ServerSocket ss = new ServerSocket(9990);
                while(true){

                    Socket sc = ss.accept();
                    Help hp = new Help();
                    BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
                    String compute = br.readLine();

                    Maths(compute);
                    PrintWriter pw = new PrintWriter(sc.getOutputStream());

                    if(compute.equals("help")){
    //                  pw.println(hp.noOfLines());
                        pw.println(hp.menu());
                    }

                    if(compute.equals("exit")){
                        ss.close();
                    }

                    else{
                        pw.println(answer); 
                    }

                    pw.flush();
                }

            }

            catch (Exception ee){
                ee.printStackTrace();
            }

        }

        static double Maths(String compute){

          String message[] = compute.split(" ");


          if(message[0].equalsIgnoreCase("Help"))
          {
              return -2;
          }

          if(message[0].equalsIgnoreCase("Exit"))
          {
              return -1;
          }


          double rad = 0;

          double a = Integer.parseInt(message[0]);
          double b = Integer.parseInt(message[2]);

          if(message[1].equalsIgnoreCase("Sin")){
                rad = Math.toRadians(a);
                answer = Math.sin(rad);
            }
            if(message[1].equalsIgnoreCase("Cos")){
                if(a==90 || a==270){
                    answer = 0;
                }
                else{
                    rad = Math.toRadians(a);
                    answer = Math.cos(rad);
                }
            }
            if(message[1].equalsIgnoreCase("Tan")){
                if(a==90 || a==270){
                    System.out.println("Invalid Calculation");
                    answer =  0;
                }
                else if(a==45 || a==135){
                    rad = Math.toRadians(a);
                    answer = Math.tan(rad);
                }
                rad = Math.toRadians(a);
                answer = Math.tan(rad);
            }
        if(message[1].equalsIgnoreCase("Power") || (message[1].equalsIgnoreCase("^")))
        {
            answer = Math.pow(a, b);  
        }

          if(message[1].equalsIgnoreCase("Multiply") || (message[1].equalsIgnoreCase("*")))
          {
              answer = a*b;  
          }
          if(message[1].equalsIgnoreCase("Add") || (message[1].equalsIgnoreCase("+")))
          {
            answer = a+b;
          }
          if(message[1].equalsIgnoreCase("Subtract") || (message[1].equalsIgnoreCase("-")))
          {
            answer = a-b;
          }
          if(message[1].equalsIgnoreCase("Divide") || (message[1].equalsIgnoreCase("/")))
          {
            answer = a/b;
          }
            return answer;

      }


    }
客户端代码:

package One;

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

    public class ClientCalculator {


        public static void main(String[] args) {

            Socket sc;  

            System.out.println("Client...");

            while(true){

                try
                {
                    Scanner sin = new  Scanner(System.in);
                    String question = sin.nextLine(); 
                    System.out.println("Processing: " + question);


                    sc = new Socket("localhost",9990);

                    PrintWriter pw = new PrintWriter(sc.getOutputStream());

                    pw.println(question);   
                    pw.flush();

                    BufferedReader br = new BufferedReader(new InputStreamReader(sc.getInputStream()));
                    String answer = br.readLine();
                    System.out.println(question + " = " + answer);
//                  sc.close();
//                  sin.close();
                }

                catch(Exception ee){

                }
            }
     }



    }
帮助菜单:

package One;

public class Help {

String menu(){

    String helpMenu = 
    "Instructions for the calculator " +
    "Input the number followed by space and then by word or operator and by number to get result " +
    "e.g. 5 + 5. or 30 Sin 30 - where 30 is the angle. " + 
    "Options are " + 
    "Multiply or (*) " + 
    "Add or (+) " +  
    "Subtract or (-) " + 
    "Divide or (/) " + 
    "Sin, Cos, Tan ";

    return helpMenu;

}


//  String noOfLines() {
//      
//      return "9";
//  }

}
运行代码:

package One;

public class TestClass {

    public static void main(String[] args) {

        new ServerCalculator();

    }

}
使用“\n”字符插入新行

替换

String helpMenu = 
    "Instructions for the calculator " +
    "Input the number followed by space and then by word or operator and by number to get result " +
    "e.g. 5 + 5. or 30 Sin 30 - where 30 is the angle. " + 
    "Options are " + 
    "Multiply or (*) " + 
    "Add or (+) " +  
    "Subtract or (-) " + 
    "Divide or (/) " + 
    "Sin, Cos, Tan ";


那是因为你用一行字发送它们。您需要在每行后面追加一个
换行符(\n)
,以便在不同的行中显示它们

另请注意:-如果要使用过多的字符串连接,最好使用
StringBuilder

您可以将菜单方法更改为:

String menu(){
    StringBuilder helpMenu = new StringBuilder();

    helpMenu.append("Instructions for the calculator \n")
            .append("Input the number followed by space and then by word or operator and by number to get result \n")
            .append("e.g. 5 + 5. or 30 Sin 30 - where 30 is the angle. \n")
            .append("Options are: \n")
            .append("\tMultiply or (*) \n")
            .append("\tAdd or (+) \n")
            .append("\tSubtract or (-) \n")
            .append("\tDivide or (/) \n")
            .append("\tSin, Cos, Tan \n");

    return helpMenu.toString();

}

您必须在客户端的readline方法周围添加while循环:

String answer = null;
while((answer=br.readLine()) != null)
{
//print answer
}

最好使用常量而不是硬编码:
System.getProperty(“line.separator”)

我曾尝试使用StringBuilder,但问题是它只打印出第一行,仅此而已。@Saint。。您是否在每行末尾添加了一个
换行符
?这对于在控制台上打印菜单很有效,但只起作用一次,之后我无法向服务器发送任何其他命令。@ValentijnSpruyt。。什么?你是说,每个问题的答案都是重复的吗?改进你的思维。我正在检查代码,OP说之前的更改不起作用。见前面的评论。同时,我想船长公布了他的答案。至少不要因为窃取了这样的答案而受到责备。即使这样,我也会为您删除编辑。尝试,不起作用只打印第一行,之后什么也不打印。这是因为在客户端代码中,您正在调用
br.readLine()仅一次。这只读取第一行。您应该多次调用它以读取后续行。可能在某个循环中。这对于在控制台上打印菜单很好,但它只工作一次,之后我无法向服务器发送任何其他命令。您没有关闭服务器上的套接字。如果我关闭套接字,我将关闭服务器。
String answer = null;
while((answer=br.readLine()) != null)
{
//print answer
}