How to Review Input in Java From the Keyboard
The Java programming language includes library functions to capture keyboard input. Those functions typically return objects of the "String" class. However, not all programs can accept alphanumeric strings as valid inputs; some fields only take numeric values. You can write Java code that reviews keyboard input to determine if it is numeric or alphanumeric.
Instructions
-
-
1
Include the following line at the beginning of your Java program:
import java.io.*;
import java.lang.Exception.*;
-
2
Read keyboard input into a Java String, as in the following sample code:
String kbdInput;
InputStreamReader myStream = new InputStreamReader(System.in);
BufferedReader myReader = new BufferedReader(myStream);
kbdInput = myReader.readLine();
-
-
3
Determine if the String contains a valid number by attempting to convert its contents to a number and catching the potential error condition, as in the following sample code:
try {
int numericValue = Integer.parseInt(kbdInput);
} catch (NumberFormatException e) {
// kbdInput is an alphanumeric String and not a valid Integer
}
-
1