Workshop 2007 JRE Java Support
Java Applets

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. 


  1. Make the java class  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. 



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

  1. 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.


  1. Declare the double variable n and initialize to 0.0. We will use n to retrieve our data from nField.


  1. 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.


  1. 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:



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.

  1. 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.




Inputting Data from the Applet:

Using the Convert Class