我有一个程序基本上返回一个字符串,有时可以一行(工作正常)但其他时候它可能是多行导致我的问题。基本上我有用户选择一个发送到第二个程序的选项,并根据该选项返回一个特定的字符串。但是,如果我将用户选择放在我的循环之外,如果返回的String是多行,则可以正常工作,但我需要它继续提示用户选择菜单,直到他们选择退出为止。这是代码:
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;
}
}
正如我上面提到的,返回多行字符串很好,但它不会再提示用户选择选项。如果我在循环内移动用户选择并返回多行字符串,则会打印一行,询问用户选择,打印第二行,询问用户选择,打印第三行,询问用户选择... < / p>
答案 0 :(得分:1)
代码很难遵循。更多背景会有所帮助。什么是&#34;输入&#34;? (即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.
//...
答案 1 :(得分:0)
如果您想多次与客户端和服务器通信,则必须进行两次循环。
看起来可能是这样的:
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;
}
}