How to use Keyboard Class
As Java does not support a simple APIs for Keyboard Input, we created
a class called "Keyboard" (in file Keyboard.java),
which you can use in your program. The Keyboard class facilitates keyboard
input by abstracting details about input parsing, conversions, and exception
handling. This class reads from standard input (keyboard) and converts
the characters into an appropriate type based on the method (Java term,
same as a function in C) you call. There are many public methods available
in Keyboard class, however, you often need to call these five methods:
-
Keyboard.readString()
-
Keyboard.readWord()
-
Keyboard.readChar()
-
Keyboard.readBoolean()
-
Keyboard.readInt()
-
Keyboard.readLong()
-
Keyboard.readFloat()
-
Keyboard.readDouble()
For syntax of above methods click on this.
Few important notes:
-
Keyboard class does not have main().
You treat this class like a library where you only call or use the
Keyboard methods as necessary. You can't run Keyboard class on its own.
-
Including or linking the Keyboard class.
Unlike C with #include, you don't need to do anything in Java to link
the Keyboard file. When you compile using javac, it will automatically
compile Keyboard.java provided that the file is in the same
directory. See the example below for more information.
-
Keyboard class uses static for all its methods.
In Java, static refers to a method or variable that is not attached
to a particular object, but rather to the class as a whole. This means,
you don't need to create an object of Keyboard before using its methods.
-
To use one or more public Keyboard methods, type: Keyboard.methodName()
-
For example: Keyboard.readString() or Keyboard.readDouble()