Can single String contain multiple lines?

后端 未结 2 1647
一生所求
一生所求 2021-01-25 23:33

For example if I assign multiple lines to a string as so:

while ((line = reader.readLine()) != null)
        {
            output += line + \"\\n\";
        }


        
相关标签:
2条回答
  • 2021-01-25 23:45

    why not just move this to outside the while loop?

        System.out.print("Enter your choice: ");
        fromClient = stdIn.readLine().trim();
    
    0 讨论(0)
  • 2021-01-25 23:59

    There is another mistake in code: while ((fromServer = input.readLine())+"\n" != null). It will be always true. You should only check: while ((fromServer = input.readLine()) != null).

    Also if I understand your requirements correctly, your code should be something like below:

    String fromServer = "";
    String line;
    while ((line = input.readLine()) != null) {
        fromServer += line + "\n"; // collect multiline strings into fromServer
    }
    
    System.out.println("Server: " + fromServer);            
    if (fromServer.equals("Bye"))
        break;          
    
    System.out.print("Enter your choice: ");
    fromClient = stdIn.readLine().trim();
    
    if(fromClient.equals("1"))
    {
        System.out.println("Client: " + fromClient);
        output.println(fromClient);
    }
    
    0 讨论(0)
提交回复
热议问题