KeyBoard Input Class
by , 11-08-2011 at 06:39 PM (729 Views)
Taking 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.
Usage example:Java Code: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) }
Java Code:char choice = KeyboardInput.readChar();









Email Blog Entry
License4J 4.0
Today, 12:23 AM in Java Software