2012-11-13 3 views
3

저는 클라이언트와 서버가있는 작은 프로그램을 작성하고 있습니다. 서버 프로그램에는 계산기 프로그램이 들어 있습니다. 서버와 클라이언트가 실행되는 동안 클라이언트는 입력하고 수식을 입력 할 수 있습니다. 2 + 2와 서버가 그것을 계산하고 클라이언트에게 응답을 보냅니다. 프로그램에는 도움말 옵션도 있어야하므로 명령 도움말이 클라이언트에서 서버로 전송되면 서버는 도움말 메뉴를 반환해야합니다. 내 문제는 도움말 메뉴를 반환하지만 한 줄에 모두 콘솔에 별도의 줄로 인쇄하지 않는 것입니다. 어떤 도움을 주셔서 감사합니다.새 줄이있는 문자열을 읽는 JAVA 클라이언트 서버

서버 코드 :

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"; 
// } 

} 

RUN 코드 :

package One; 

public class TestClass { 

    public static void main(String[] args) { 

     new ServerCalculator(); 

    } 

} 

답변

1

:

당신은 당신의 메뉴 방식을 변경할 수 있습니다 하드 코딩 : System.getProperty("line.separator");

+0

콘솔에서 메뉴를 인쇄 할 때 제대로 작동하지만 한 번만 작동하고 이후에는 서버에 다른 명령을 보낼 수 없습니다. – Saint

+0

서버에서 소켓을 닫지 않았습니다. –

+0

소켓을 닫으면 서버를 종료합니다. – Saint

2

새 행을 삽입 할 때 "\ 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 "; 

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

시도한 후 첫 번째 줄만 인쇄하고 이후는 아무것도 인쇄하지 않습니다. – Saint

+0

그것은 클라이언트 코드에서'br.readLine();'을 한 번만 호출하기 때문입니다. 이것은 단지 첫 번째 행을 읽습니다. 후속 라인을 읽으려면 여러 번 호출해야합니다. 일부 반복 될 수 있습니다. –

2

그게 전부를 교체합니다. 각 행 다음에 newline (\n)을 추가해야 여러 행에 표시 할 수 있습니다.

참고 : 너무 많은 문자열 연결을 사용하려는 경우 StringBuilder을 사용하는 것이 더 좋습니다. 또한 대신 상수를 사용하는 것이 바람직하다

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

: 클라이언트에 ReadLine 메서드 주위에 while 루프를 추가 할 필요가

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

} 
+0

또는'StringBuffer' ... :) –

+0

@ShashankKadne .. 네 StringBuffer도 작동합니다. –

+0

StringBuilder를 사용하려고 시도했지만 문제는 첫 번째 줄만 인쇄하면된다는 것입니다. – Saint

관련 문제