Lesson 3.5 Numeric Input
Getting Numeric Input
Most languages have an easy way to read text input from the keyboard and then convert the result to a numeric value before storing it in a numeric variable. Programmers coming to Java from another language such as Pascal or C are often baffled by Java's lack of such a facility. Some have even gone to great lengths to reproduce Pascal's Read facility or C's scanf() function.
There are two reasons for Java's lack of such a facility:
- Such functions are relics of a bygone console-mode mentality. Today, interactive programs should use a GUI [Graphical User Interface], and not try to reproduce the "glass teletype" of the 1960s and 1970s
- Java cleanly separates input-output facilities [reading and writing data] from its conversion facilities.
Numbers and Strings
When a user types the number 123 from the keyboard, whether using a modern GUI or using the console, what is actually stored in memory are the three binary values:
0000-0000 0011-0001
0000-0000 0011-0010
0000-0000 0011-0011 |
representing the three Java char values '1', '2', and '3' stored in a Java String object.
If the user is entering values intended to be used in a calculation, [and not a street address, for instance], those three char values will have to be converted from text to the binary integer 123:
| 0000-0000 0000-0000 0000-0000 0111-1011 |
This process--turning human-readable text Strings into binary numbers, [and its alter-ego, turning binary numbers into human-readable text Strings], is the job of conversion. [To find out how to turn binary numbers into text output, turn to the next section, Numeric Formatting.]
Integer Conversion
The first step is to get some user input. The section "Buttons and TextFields" in this lesson showed you how to do that. If your applet has a TextField named n1TF, you can retrieve the text from n1TF like this:
| String s1 = n1TF.getText(); |
Once you've retrieved the String from the TextField, you can convert it to an int value by using the "magical" incantation:
| int n1 = Integer.parseInt(s1); |
The Integer class is one of Java's "wrapper" classes that provides methods useful for manipulating primitive types. Its parseInt() method will convert a String into an int, if possible.
Remember that primitive types don't have methods and are not extensible. Wrapper classes allow you to perform additional operations on primitive types and to extend them by creating a class whose single field is a primitive value like this.

An Example
Here is an example applet, ConvertInt.java, that takes the values from two TextFields and stores the sum in the Label ans. Carefully read the program until you understand how data flows from the user, into the numeric variables n1 and n2, and back to the user.
To run the applet, type a number into each TextField, and then press ENTER while your cursor is inside the second TextField.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ConvertInt extends Applet
implements ActionListener
{
TextField n1TF = new TextField(10);
TextField n2TF = new TextField(10);
Label ansLbl = new Label("____________");
public void init()
{
add(n1TF);
add(n2TF);
n2TF.addActionListener(this);
add(ansLbl);
}
public void
actionPerformed(ActionEvent e)
{
String s1 = n1TF.getText();
String s2 = n2TF.getText();
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int ans = n1 + n2;
ansLbl.setText("Sum = " + ans);
}
}
|
What is the Value of "Twelve"
Sometimes, a user will enter a value which cannot be successfully converted to an integer. For instance, if you type the word "one" into the TextField above, and then press Enter, Java throws an exception, but the rest of the program continues normally.
Later in the course, you'll see how you can trap such errors, and perhaps give the user some help. For now, just ignore them. If you want to see the exception occuring, you can view the Java Console from the Communicator|Tools menu.
Floating-Point Input
For floating-point input the process is very similar to that used for integers: Get a text value from the user, then change the value to a double or a float. [There are actually several ways to do this. I'll present one method here, and another method in your text. You can use the method that you prefer.]
The process is somewhat different, however. Because Java 1.1 has no Double.parseDouble() method, similar to the one you used for integer conversion, you must use one of these methods if you want your code to work in a Java 1.1-enabled browser.
Here are the steps to follow:
- Retrieve the text from your TextField, and store it in a String.
- Create a new Double object, passing your String to the Double(String) constructor. [With the Integer class, we were able to avoid this by using a static method. You'll learn more about static methods in the next lesson.]
- Extract the primitive double from your Double object by sending it the doubleValue() message.
Here's a code fragment that follows these three steps and that uses the names bigD and littleD for the Double object and the double primitive, respectively:
String sValue = n1TF.getText();
Double bigD = Double.valueOf(sValue)
// This works just as well
// Double bigD = new Double( sValue );
double littleD = bigD.doubleValue(); |
You can, if you like, wrap the whole thing up in one magical line like this:
| double d = Double.valueOf(n1TF.getText()).doubleValue(); |
Of course, if you are certain that your clients will only be using the Java2 browser plugin, or if you are writing a Java2 application, you can use the Java2 Double.parseDouble() method, just like you used Integer.parseInt().
String sValue = n1TF.getText();
double d = Double.parseDouble(sValue); |
For this course, however, use one of the Java 1.1 methods.
Something to Talk About
The program ConvertInt.java, shown in the Numeric Input section, adds two integers together and displays their sum. How would you change the actionPerformed() method to add two doubles instead of two ints?
Please continue to the next section of this lesson.
|