1

我有一个程序基本上返回一个字符串,该字符串有时可能是一行(工作正常),但有时它可能是多行,这会导致我出现问题。基本上我让用户选择一个发送到第二个程序的选项,并根据该选项返回一个特定的字符串。但是,如果我将用户选择放在我的循环之外,如果返回的字符串是多行,它工作正常,但我需要它不断提示用户选项菜单,直到他们选择退出。这是代码:

System.out.print("Enter your choice: ");
fromClient = stdIn.readLine().trim();

while ((fromServer = input.readLine()) != null)
    {
        System.out.println("Server: " + fromServer);            
        if (fromServer.equals("Bye"))
        break;          


        if(fromClient.equals("1"))
        {
            System.out.println("Client: " + fromClient);
            output.println(fromClient);

        }
        if(fromClient.equals("2"))
        {
            System.out.println("Client: " + fromClient);
            output.println(fromClient);

        }
        if(fromClient.equals("3"))
        {
            System.out.println("Client: " + fromClient);
            output.println(fromClient);

        }
        if(fromClient.equals("4"))
        {
            System.out.println("Client: " + fromClient);
            output.println(fromClient);
            break;

        }


    }

正如我上面提到的,这很好地返回了多行字符串,但它不再提示用户选择选项。如果我在循环内移动用户选择并返回多行字符串,它将打印一行,询问用户他们的选择,打印第二行,询问用户他们的选择,打印第三行,询问用户他们的选择......

4

2 回答 2

1

该代码相当难以遵循。更多上下文会有所帮助。什么是“输入”?(即 fromServer = input.readLine())

无论如何,无论您的服务器发送多少行,在提示用户输入之前您一次只能读取 1 行。在发送客户端命令之前尝试处理所有服务器的响应。例如:

boolean shouldExit = false;

while ((fromServer = input.readLine()) != null){
    System.out.println("Server: " + fromServer);                     
    if (fromServer.equals("Bye")){
        shoudExit = true;
        break;
    }
}

if (shouldExit) System.exit(0)  // Or whatever you want to do

//Now handle sending your client's command to the server.
//...
于 2012-09-11T17:25:43.560 回答
0

如果要多次通信客户端和服务器,则必须进行两个循环。

  1. 第一个循环将要求用户选择,启动第二个循环并根据服务器响应和用户选择做任何你想做的事情
  2. 第二个循环将从服务器读取所有行

它可能看起来像这样:

System.out.print("Enter your choice: ");
while( true ) {
    fromClient = stdIn.readLine().trim();

    StringBuilder responseSb = new StringBuilder();
    while( ( fromServer = input.readLine() ) != null ) {
        responseSb.append( fromServer );
        responseSb.append( "\n" );
    }

    String response = responseSb.toString().trim();

    System.out.println( "Server: " + response );
    if( response.equals("Bye") ) {
        break;
    }


    if(fromClient.equals("1"))
    {
        System.out.println("Client: " + fromClient);
        output.println(fromClient);

    }
    if(fromClient.equals("2"))
    {
        System.out.println("Client: " + fromClient);
        output.println(fromClient);

    }
    if(fromClient.equals("3"))
    {
        System.out.println("Client: " + fromClient);
        output.println(fromClient);

    }
    if(fromClient.equals("4"))
    {
        System.out.println("Client: " + fromClient);
        output.println(fromClient);
        break;

    }


}
于 2012-09-11T18:03:06.097 回答