View RSS Feed

My Java Tips

KeyBoard Input Class

Rate this Entry
by , 11-08-2011 at 06:39 PM (1119 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.




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)

}
Usage example:
Java Code:
       	    char choice = KeyboardInput.readChar();

Submit "KeyBoard Input Class" to Facebook Submit "KeyBoard Input Class" to Digg Submit "KeyBoard Input Class" to del.icio.us Submit "KeyBoard Input Class" to StumbleUpon Submit "KeyBoard Input Class" to Google

Categories
Java SE

Comments