0

Facing problem while trying to print using PrintWriter.

Problem Description:

I am expecting to print the Press options first then take the user input but using out.println i can't do that. It's not printing the options while i run the program. It just waits for an input while i give the input it then prints the Press options.

Note: if i use System.out.println then it works as expected.

Tried it like below

public class Calculator {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out =  new PrintWriter(new OutputStreamWriter(System.out));
        StringTokenizer took = new StringTokenizer(" ");
        String operator;
//            System.out.println("Press '+' for Additon");
//            System.out.println("Press '-' for Subtraction");
//            System.out.println("Press '*' for multiplication");
        out.println("Press '+' for Additon");
        out.println("Press '-' for Subtraction");
        out.println("Press '*' for multiplication");
        out.println("Press '/' for Division");

        operator=in.readLine();
        switch (operator) {
            case "+":
                out.println("Add");
                break;
            case "-":
                out.println("Subtract");
                break;
            case "*":
                out.println("Multiply");;
                break;
            case "/":
                out.println("Division");
                break;
        }
        in.close();
        out.close();
    }
}

Input:

*

Output:

Press '+' for Additon
Press '-' for Subtraction
Press '*' for multiplication
Press '/' for Division

Multiply
1
  • 7
    Flush, flush, flush! Or autoFlush. Commented Feb 12, 2014 at 6:41

1 Answer 1

3

Do:

out.flush();

Before you read in, and then before you close the out.

Or you can do:

PrintWriter out =  new PrintWriter(new OutputStreamWriter(System.out), true);

What the true does is sets it to auto flush every time you print.

Suggest reviewing the Javadoc for the PrintWriter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.