java - How to close a Scanner object inside a try loop? -


 public static int take1()   {       scanner in = new scanner(system.in);       while(true)       {           try           {               system.out.print("\nhow many coloms want = ");               return in.nextint();           }           catch(exception e )           {               system.out.println("sorry,please enter no.");               in.next();           }        }    } 

how close scanner object , if close object using or try resources closes system.in , , cant read stream more once. best method this?

put finally block , close open resource.

  • java block block used execute important code such closing connection, stream etc.
  • java block executed whether exception handled or not.

     try   {       system.out.print("\nhow many coloms want = ");       return in.nextint();   } catch(exception e ){             system.out.println("sorry,please enter no.");             in.next();    }finally{             in.close();    } 

edited per naman gala

check if exception occured don't close let go next loop util no. entered otherwise close it.

public static int take1()     {         boolean isexceptionoccured=false;         scanner in = new scanner(system.in);         while(true)         {             try             {                 system.out.print("\nhow many coloms want = ");                 isexceptionoccured=false;                 return in.nextint();             }             catch(exception e )             {                 isexceptionoccured=true;                 system.out.println("sorry,please enter no.");                 in.next();             }finally{                 if(!isexceptionoccured){                 in.close();                 system.out.println("resource closed");                 }             }          }      } 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -