Reading Input the Keyboard Class The Keyboard class
Reading Input -the Keyboard Class The Keyboard class is NOT part of the Java standard class library The Keyboard class is in package cs 1. It provides several static methods for reading particular types of data from standard input. n n n n public public static static String read. String() String read. Word() boolean read. Boolean() char read. Char() int read. Int() long read. Long() float read. Float() double read. Double()
Keyboard Code Example import cs 1. Keyboard; public class Read. Keyboard. Using. Keyboard. Class{ public static void main(String[] args) { int qty; double price, amount. Due; System. out. print("Enter quantity purchased: "); qty = Keyboard. read. Int(); System. out. print("Enter the unit price: "); price = Keyboard. read. Double(); amount. Due = price * qty; System. out. println("Amount due: " + amount. Due); } }
Install Keyboard – Method 1 Copy the cs 1. jar file n n Paste it in the C: jdk 1. 3jrelibext directory If the above doesn’t work by itself, then also paste it in C: Program FilesJava. SoftJRE1. 3libext
Install Keyboard – Method 2 Create a cs 1 subdirectory to the directory containing your java programs Copy and compile Keyboard. java into the cs 1 subdirectory Homework directory | +-Java source files | +- cs 1 subdirectory | +- Keyboard. java +- Keyboard. class
Install Keyboard – Method 3 Copy Keyboard. java into the same directory as your programs. Remove the import statement from the code that calls Keyboard
Reading Input –JOption. Pane import javax. swing. JOption. Pane; public class Read. Keyboard. Via. JOption. Pane{ public static void main(String[] args) { int qty; double price, amount. Due; String temp; temp = JOption. Pane. show. Input. Dialog ("Please enter the quantity purchased: "); qty = Integer. parse. Int(temp); temp = JOption. Pane. show. Input. Dialog ("Please enter the unit price: "); price = Double. parse. Double(temp); amount. Due = price * qty; JOption. Pane. show. Message. Dialog (null, "Amount due: " + amount. Due); } }
Reading Input – java. io import java. io. *; public class Read. Keyboard. Via. System. In{ public static void main(String[] args) throws IOException { int qty; double price, amount. Due; Buffered. Reader br = new Buffered. Reader (new Input. Stream. Reader (System. in)); System. out. print("Please enter the quantity purchased: "); qty = Integer. parse. Int(br. read. Line()); System. out. print("Please enter the unit price: "); price = Double. parse. Double(br. read. Line()); amount. Due = price * qty; System. out. println("Amount due: " + amount. Due); } }
- Slides: 7