Akerr Stephen
Akerr Stephen

Reputation: 21

Odd error related to Stream being closed

I am learning Java and I wrote a method to update a record in a file. The problem I am having is when I ask the user if they would like to look for another file my reader is closed or is unable to assign any input to it.

protected boolean Update() throws InputMismatchException
{
    RoomService Init =new RoomService();
    Scanner input = new Scanner(System.in);

        try {
            boolean ans= true;

         while(ans)
         {
            System.out.println("Please enter room number.");
            String id = input.next();
            Init.Update(id);
            System.out.println("Press Enter to Add more or no to exit");
            String choice = input.nextLine();// Skips this line 
                if (choice.equalsIgnoreCase(""))
                {
                    continue;
                }
                else if(choice.equalsIgnoreCase("no"))
                {
                    ans= false;
                }
                  else 
                  {
                      System.err.println("Wrong input");
                        throw new IOException();
                  }
         }

        } catch (IOException e) {
            e.printStackTrace();
            fail=true;
        }
    return fail;
}

Wondering what exactly is blocking me from entering anything I also used BufferedReader input = new BufferedReader(new InputStreamReader (System.in))

Thanks.

Edit:

Using Scanner Error is : java.util.NoSuchElementException

Using BufferedReader error is: java.io.IOException: Stream closed

Upvotes: 0

Views: 54

Answers (1)

Boann
Boann

Reputation: 50031

If there is anywhere else in your code you are using a Scanner wrapped around System.in, make sure you do not call close() on it. A Scanner itself has no resources that need to be closed, unless you want to close the underlying input source, which for a Scanner wrapped around System.in, you don't, because that prevents all future input.

Upvotes: 1

Related Questions