KeyBoard Input Class
11 April 2007Taking input from keyboard involves various steps. Lot of people ask for some ready made class which will serve the purpose. Following class is a good choice. You can use “readInt()”, “readDouble()”, “readChar()” and “readString()” methods according to your needs.
import java.io.*; public class KeyboardInput { static BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); public static int readInt () { while (true) { try{ String line = stdin.readLine(); int value = Integer.parseInt(line); return value; } catch(java.lang.NumberFormatException e){ ; } catch(IOException e){ ; } } } // end readInt () public static int readInt (String text) { System.out.print(text); while (true) { try{ String line = stdin.readLine(); int value = Integer.parseInt(line); return value; } catch(java.lang.NumberFormatException e){ ; } catch(IOException e){ ; } } } // end readInt (String text) public static double readDouble () { while (true) { try { String line = stdin.readLine(); double value = Double.valueOf(line).doubleValue(); return value; } catch (java.lang.NumberFormatException e){ ; } catch (IOException e){ ; } } } // end readDouble() public static char readChar () { while (true) { try { String line = stdin.readLine(); char value = line.charAt(0); return value; } catch (IOException e){ ; } } } // end readChar() public static String readString (){ while(true) { try { return stdin.readLine(); } catch (IOException e) { ; } } } // end readString() public static String readString (String text){ System.out.print(text); while(true) { try { return stdin.readLine(); } catch (IOException e) { ; } } } // end readString(String text) } Usage example: char choice = KeyboardInput.readChar();
Related Posts:
Top Of Page | Trackback
If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.
It will look like this: KeyBoard Input Class
Hello,
Just thought i would comment and leave my appreciation. I recently stumbled upon your blog whilst looking for a premade Keyboard input class.
Thanks for posting!
Have subsequently used the class in one of my educational projects.
Thank you very much. Keep up good work. You have a very informative, helpful Blog!!
Hi
Thank you very much for submitting this wonderful Keyboard class. I compiled and then placed in the same folder where my program was. When I checked for methods readInt and readString, I worked well. But It didn’t work for readChar and compiler issued error for this. Could you correct all and reupload the same?
Once again, thanks for you for your work
Sanjay Maurya