Download and Import the Convert Class
We’re now going to modify our existing program so that we can take an integer n from the GUI via the text field nField and then add together the numbers 1 thru n. This process is a little bit more complicated, but the ability to input information through the GUI will allow us to do all sorts of interesting things when we program.
- Make the java class Convert.java available to your project. Download and save the file Convert2.0.jar in a place that you can remember. The Convert class is archived in this file in the package com.jimrolf.convert.
- Add the convert package to your class path. You must let Day2Project know where this .jar is located, so right-click on Day2Project and choose Properties/Libraries. Click on “Add Jar/Folder” and navigate to the file you just saved. After choosing Convert2.0.jar, click “Ok” and return to your project.
- Import the Convert class into Day2Applet.java. Your project now knows where the convert package is located. But you must still inform your applet class which files you need out of this package. It turns out that there’s only one class in the package— the Convert class. So scroll up to the top of your Day2Applet.java file. You will see the package declaration
package edu.usafa.day2;
Underneath this, type
import com.jimrolf.convert.Convert;
This last line means “import the
Convert
class from the com.jimrolf.convert package.”
Convert String Input
- Declare a String variable, inputString. While it’s not absolutely required to initialize a variable when declaring it, it’s good programming practice. With non-primitive data types, you may initialize them as null. It’s usually a good idea to group all variable declarations at the beginning of the method.
- Declare the double variable n and initialize to 0.0. We will use n to retrieve our data from nField.
- Retrieve String from the nField and store in inputString. You will want to utilize the getText()method. The important point here is all information coming through the GUI is a String. We will need to convert this string to an integer before proceeding.
- Convert inputString to type int and store it in n. Here’s where the Convert class comes in handy. There are several methods in this class. One of them is Convert.toInt() that accepts an argument of type String and returns the equivalent int. Here’s how you want to use it:
inputNumber=Convert.toInt(inputString);
The Convert class is a class with static methods. What this means for you is that the methods can be called with out first instantiating a Convert object (more about this in another lesson). There are several other methods in the Convert class that you may want to use, including Convert.toDouble(String). See the java docs or this web page for more details.
- Finally, add the numbers from 1 through n and output to loopLabel.
Here’s the code that I used to accomplish all of this:
See Sample Code 2 to check work.