70 likes | 237 Views
Reading Input -- the Keyboard Class. The Keyboard class is NOT part of the Java standard class library The Keyboard class is in package cs1 . It provides several static methods for reading particular types of data from standard input. public static String readString()
E N D
Reading Input --the Keyboard Class • The Keyboardclass is NOT part of the Java standard class library • The Keyboard class is in package cs1. • It provides several static methods for reading particular types of data from standard input. • public static String readString() • public static String readWord() • public static boolean readBoolean() • public static char readChar() • public static int readInt() • public static long readLong() • public static float readFloat() • public static double readDouble()
Keyboard Code Example import cs1.Keyboard; public class ReadKeyboardUsingKeyboardClass{ public static void main(String[] args) { int qty; double price, amountDue; System.out.print("Enter quantity purchased: "); qty = Keyboard.readInt(); System.out.print("Enter the unit price: "); price = Keyboard.readDouble(); amountDue = price * qty; System.out.println("Amount due: " + amountDue); } }
Install Keyboard – Method 1 • Copy the cs1.jar file • Paste it in the C:\jdk1.3\jre\lib\ext directory • If the above doesn’t work by itself, then also paste it in C:\Program Files\JavaSoft\JRE\1.3\lib\ext
Install Keyboard – Method 2 • Create a cs1 subdirectory to the directory containing your java programs • Copy and compile Keyboard.java into the cs1 subdirectory Homework directory | +-Java source files | +- cs1 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 –JOptionPane import javax.swing.JOptionPane; public class ReadKeyboardViaJOptionPane{ public static void main(String[] args) { int qty; double price, amountDue; String temp; temp = JOptionPane.showInputDialog ("Please enter the quantity purchased: "); qty = Integer.parseInt(temp); temp = JOptionPane.showInputDialog ("Please enter the unit price: "); price = Double.parseDouble(temp); amountDue = price * qty; JOptionPane.showMessageDialog (null,"Amount due: " + amountDue); } }
Reading Input – java.io import java.io.*; public class ReadKeyboardViaSystemIn{ public static void main(String[] args) throws IOException { int qty; double price, amountDue; BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); System.out.print("Please enter the quantity purchased: "); qty = Integer.parseInt(br.readLine()); System.out.print("Please enter the unit price: "); price = Double.parseDouble(br.readLine()); amountDue = price * qty; System.out.println("Amount due: " + amountDue); } }