Anda di halaman 1dari 5

Keyboard Input

http://www.cs.ucl.ac.uk/teaching/D0a1/additionalnotes/KeyboardInput.html

Keyboard Input
These notes show how to use a class called KeyboardInput for reading values typed in at the keyboard. The class brings together a collection of useful input methods that you can call from your programs. The class is taken from the text book, where it is used in some of the examples and is listed in Appendix A3. Using the class you can read values of the following types: int long double float char String You have to type a value using the correct format for that type. For example, 123 would be a valid int value but abc would not be. Reading input is always tricky as you have to deal with all the strange things that someone may type in! If you type something that cannot be recognised as a value of the type being asked for, a default value is returned, rather than an error being reported.

Using KeyboardInput
To use the KeyboardInput class save the source code into a file called KeyboardInput.java (you can use cut and paste from the web page version of these notes). Then compile the code to produce the file KeyboardInput.class. This file, or a copy of it, should then be placed in any directory you are using when working on your exercises. (If you want to be more sophisticated and avoid making copies of the .class file investigate how to use the CLASSPATH environment variable.) Before any input can be read by a program you need to create a KeyboardInput object using the KeyboardInput class. Do this by having a line in your program that looks like this:
KeyboardInput in = new KeyboardInput() ;

This line must appear before you do any input and will give you a variable called in that references the KeyboardInput object. Once you have an object you can use it to call input methods. For example, to read in an integer you would use:
int x = in.readInteger() ;

When this statement is executed, the program will wait for you to type in some input. The input must be ended by pressing the <return> key, otherwise nothing will happen! Once the input has been read an attempt will be made to recognise the characters that were typed as an integer of type int. If successful the int value will be returned. If not, then a default value of 0 is returned. To let someone using your program know that input is expected, it is a good idea to print a message asking for the input. For example:
System.out.print("Type a floating point number: ") ; double d = in.readDouble() ;

1 of 5

09/05/2012 6:06 PM

Keyboard Input

http://www.cs.ucl.ac.uk/teaching/D0a1/additionalnotes/KeyboardInput.html

Note the use of print, rather than println, so that the input follows the request on the same line. The following test program shows the use of all the input methods provided by the class. To run this program, save the source code to a file called KeyboardInputTest.java and compile it, having first made sure that a copy of KeyboardInput.class is in the same directory.
/** ... */ public class KeyboardInputTest { public static void main(String[] args) { KeyboardInput in = new KeyboardInput() ; System.out.print("Type an integer: ") ; int n = in.readInteger() ; System.out.println("Integer was: " + n) ; System.out.print("Type a long: ") ; long l = in.readLong() ; System.out.println("Long was: " + l) ; System.out.print("Type a double: ") ; double d = in.readDouble() ; System.out.println("Double was: " + d) ; System.out.print("Type a float: ") ; float f = in.readFloat() ; System.out.println("float was: " + f) ; System.out.print("Type a char: ") ; char c = in.readCharacter() ; System.out.println("char was: " + c) ; // Note that reading one character leaves the newline // character still in the input buffer. Do an extra // read to use it up. c = in.readCharacter() ; System.out.print("Type a String: ") ; String s = in.readString() ; System.out.println("String was: " + s) ; } }

Input Buffering
Input from the keyboard is buffered in an input buffer managed by the operating system. This means that all the characters typed are collected up and temporarily stored until the <return> key is pressed. The operating system keeps your program waiting while you are typing, so your program is not actaully doing anything. Only after the <return> key is pressed does your program carry on executing. While your program is waiting we say it is suspended or blocked. As a result of the buffering your program receives a whole line of characters at a time, not single characters one after another. The line of characters includes a newline character at the end - newline is the character generated by pressing <return>. When you read any type of value, except for char, the newline character is automatically removed and you don't see it. However, when you read a single character the newline is left in place and you need to do an extra readCharacter to get rid of it. You can see this being done in the test

2 of 5

09/05/2012 6:06 PM

Keyboard Input

http://www.cs.ucl.ac.uk/teaching/D0a1/additionalnotes/KeyboardInput.html

program above. So, don't forget to take this into account when reading characters. The KeyboardInput class listing:
import java.io.* ; /** * A simple input class to read values typed at the command line. If * an error occurs during input, any exceptions thrown are caught and * a default value returned. * * @version 1.0 1.7.97 * @author Graham Roberts */ public class KeyboardInput { /** * Read an int value from keyboard input. */ public final synchronized int readInteger() { // // The place to hold the data received from the keyboard so // that we can parse it to find the int value. // String input = "" ; // // Read a String of characters from the keyboard. // try { input = in.readLine() ; } catch (IOException e) {} // // Parse the String to construct an int value. // int val = 0 ; try { val = Integer.parseInt(input) ; } catch (NumberFormatException e) {} return val ; } /** * Read a long value from keyboard input. */ public final synchronized long readLong() { // // The place to hold the data received from the keyboard so // that we can parse it to find the long value. // String input = "" ; // // Read a String of characters from the keyboard. // try { input = in.readLine() ; } catch (IOException e) {} //

3 of 5

09/05/2012 6:06 PM

Keyboard Input

http://www.cs.ucl.ac.uk/teaching/D0a1/additionalnotes/KeyboardInput.html

// Parse the String to construct a long value. // long val = 0L ; try { val = Long.parseLong(input) ; } catch (NumberFormatException e) {} return val ; } /** * Read a double value from keyboard input. */ public final synchronized double readDouble() { // // The place to hold the data received from the keyboard so // that we can parse it to find the double value. // String input = "" ; // // Read a String of characters from the keyboard. // try { input = in.readLine() ; } catch (IOException e) {} // // Parse the String to construct a double value. // double val = 0.0D ; try { val = (Double.valueOf(input)).doubleValue() ; } catch (NumberFormatException e) {} return val ; } /** * Read a float value from keyboard input. */ public final synchronized float readFloat() { // // The place to hold the data received from the keyboard so // that we can parse it to find the long value. // String input = "" ; // // Read a String of characters from the keyboard. // try { input = in.readLine() ; } catch (IOException e) {} // // Parse the String to construct a float value. // float val = 0.0F ; try { val = (Float.valueOf(input)).floatValue() ; }

4 of 5

09/05/2012 6:06 PM

Keyboard Input

http://www.cs.ucl.ac.uk/teaching/D0a1/additionalnotes/KeyboardInput.html

catch (NumberFormatException e) {} return val ; } /** * Read a char value from keyboard input. */ public final synchronized char readCharacter() { // // No need to parse anything, just get a character and return // it.. // char c = ' ' ; try { c = (char)in.read() ; } catch (IOException e) {} return c ; } /** * Read an String value from keyboard input. */ public final synchronized String readString() { // // No need to parse anything, just get a string and return // it.. // String s = ""; try { s = in.readLine() ; } catch (IOException e) {} return s ; } /** * The stream that is the keyboard wrapped so that we can read * from it sensibly. */ private final BufferedReader in = new BufferedReader(new InputStreamReader(System.in)) ; }

5 of 5

09/05/2012 6:06 PM

Anda mungkin juga menyukai