0
void order_particular() throws IOException{
        int order_choice, x;
        //Scanner sc = new Scanner(System.in);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Do you want to order something ? ");
        System.out.println("Press 1 to order or 0 to go back to main menu");
        //order_choice = sc.next().charAt(0);
        order_choice = Integer.parseInt(reader.readLine());  // Got Error here
        System.out.println("order choice : " + order_choice);
        if(order_choice == 1){
            this.order();
            System.out.println("Do you want to order more ? ");
            System.out.println("Press 1 to order or 0 to get bill");
            x = Integer.parseInt(reader.readLine());
            System.out.println("x value : " + x);
            if(x == 1){
                this.order_more();
                this.bill_more();
            }
            else
                this.bill();
        }
    }

For the above code, I got the below error

Exception in thread "main" java.io.IOException: Stream closed
        at java.base/java.io.BufferedInputStream.getBufIfOpen(BufferedInputStream.java:168)
        at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:334)
        at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:270)
        at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:313)
        at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188)
        at java.base/java.io.InputStreamReader.read(InputStreamReader.java:177)
        at java.base/java.io.BufferedReader.fill(BufferedReader.java:162)
        at java.base/java.io.BufferedReader.readLine(BufferedReader.java:329)
        at java.base/java.io.BufferedReader.readLine(BufferedReader.java:396)
        at Waiter.order_particular(Waiter.java:404)
        at Waiter.main(Waiter.java:439)

I don't know what is going on here. I never closed bufferedReader object, But it shows an error. How to solve this error?

1 Answers1

0

The exception indicates that it is System.in that has been closed already by this point.

You'll need to look at what's happening before calling order_particular(), as the problem lies there. Maybe an earlier method is inadvertently closing it; perhaps you created a BufferedReader around it in a try-with-resource block.

erickson
  • 265,237
  • 58
  • 395
  • 493
  • Thank you. I Created it in try-with-resource block. Then I removed try block, it works. Can you tell me how try-with-resource block works? – Pardha Saradhi Apr 06 '22 at 15:13
  • @PardhaSaradhi Here is [an introduction](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) to try-with-resources. [This answer](https://stackoverflow.com/a/66872301/3474) explains in detail how the compiler treats them. – erickson Apr 06 '22 at 15:18