Question

I have an assignment stating that "You can assume that input will come from standard input in a stream. You may assume that the markers have access to all standard libraries".

How do I go about reading several lines/inputs and saving all the inputs as one string and then outputting that string from a function?

Currently this is my function, but it's not working properly, at one stage it wasn't reading more than one line and now it doesn't work at all.

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;
}

Thank you for the assistance!

Was it helpful?

Solution

The problem is you're calling reader.readLine() three different times, so you'll end up comparing two completely different strings and then recording yet another one.

Also, it's generally frowned upon to compare strings using == (as comparing Objects with == asks if they are the same actual object (yes, Java's forgiving in that regard with strings, but it's still frowned upon)).

You'll need to do something more akin to:

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;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top