簡體   English   中英

使用標准/輸出流作為字符串輸入/輸出

[英]Using the standard/output stream as string input/output

我有一個作業說明,“您可以假設輸入將來自流中的標准輸入。您可以假設標記可以訪問所有標准庫”。

如何讀取多行/輸入並將所有輸入保存為一個字符串,然后從函數輸出該字符串?

目前這是我的功能,但無法正常工作,在某一階段讀取的內容不止一行,現在根本不起作用。

public static String readFromStandardIO() {

    String returnValue = "";

    String newLine = System.getProperty("line.separator");
    System.out.println("Reading Strings from console");

    // You use System.in to get the Strings entered in console by user
    try {
        // You need to create BufferedReader which has System.in to get user
        // input
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        String userInput;
        System.out.println("Enter text...\n");
        while (!(reader.readLine() == reader.readLine().trim())) {
            userInput = reader.readLine();
            returnValue += userInput;
        }

        System.out.println("You entered : " + returnValue);
        return returnValue;

    } catch (Exception e) {

    }
    return null;
}

感謝您的幫助!

問題是您要在三個不同的時間調用reader.readLine() ,因此最終將比較兩個完全不同的字符串,然后記錄下另一個字符串。

而且,通常不贊成使用==比較字符串(因為將Object與==比較會詢問它們是否是相同的實際對象(是的,Java在這方面允許使用字符串,但仍然不贊成使用))。

您將需要執行以下操作:

public static String readFromStandardIO() {

    String returnValue = "";

    System.out.println("Reading Strings from console");

    // You use System.in to get the Strings entered in console by user
    try {
        // You need to create BufferedReader which has System.in to get user
        // input
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String userInput;
        System.out.println("Enter text...\n");
        while (true) {
            userInput = reader.readLine();
            System.out.println("Finally got in here");
            System.out.println(userInput);
            returnValue += userInput;
            if (!userInput.equals(userInput.trim())) {
                break;
            }
        }

        System.out.println("You entered : " + returnValue);

    } catch (Exception e) {

    }
    return returnValue;

}

暫無
暫無

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

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