簡體   English   中英

\\ n之后的字符串根本不在系統輸出中顯示

[英]The String after \n is not being displayed at all in the System output

因此,我正在使用TCP編寫一個簡單的服務器-客戶端程序,這是我的大學作業的一部分。 在使用UDP之前,我已經創建了一個,只需要使用TCP重做即可。 但是,我在編碼時遇到了一些有趣的事情。 顯然,我將從包含\\ n的服務器發送的字符串僅顯示\\ n之前的字符串部分。 \\ n之后的所有其他子字符串將不會顯示。 我對此感到困惑。 也許與我發送它的代碼有關?

下面的代碼來自服務器端。

PS:我已經嘗試對此進行研究,但實際上找不到任何有關我的問題的信息。 我嘗試使用“%n”,因為我在一些論壇中看到了它的建議,但這沒有用。

if(clientMessage.equals("1234"))
{
    SendMessage(incoming, "Welcome.\nMenu:\n1. Check balance\n2. Deposit\n3. Withdraw\n4. Quit");
}

public static void SendMessage(Socket incoming, String message){
//9. Initialize String to send to client
//BufferedReader output = new BufferedReader(new InputStreamReader(System.in));
    String serverMessage;
    try {
        serverMessage = message;
        //10. Initialize PrintStream using getOutputStream() method of 
        //Socket
        PrintStream send = new PrintStream(incoming.getOutputStream());
        //11. Use println() method of PrintSteam to send data to client
        send.println(serverMessage);
    } catch (IOException ex) {
        Logger.getLogger(ATMTCPServer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

因此,最后我發現了我的一個朋友指出的錯誤。 顯然,錯誤是在客戶端。 我不知道BufferedReader.readLine()只會讀取一行。 因此,這就是\\n后的子字符串不顯示的原因。 之后,我遇到了其他一些問題,但是在朋友的幫助下,我終於解決了問題並完成了任務。 感謝所有發表評論的人!

PS:我將在下面發布解決該問題的代碼。 下面的代碼來自客戶端。 我不必在服務器端進行任何更改。

serverMessage = incoming.readLine();
String[] messages = serverMessage.split("----");
for(int i = 0; i < messages.length; i++){
    if(choice.equals("2") || choice.equals("3"))
    {
        System.out.print(messages[i]);
    }
    else
    {
        System.out.println(messages[i]);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM