RHS -> Allan-> SWC Exercises MyUtils

MyUtils

 

In this exercise we'll start building our own class of utilities.

Start by creating the project "MyUtils" in NetBeans, uncheck the "Create Main Class", and create a class MyUtils.

max(int, int) and min(int, int)
We will start by putting two utilities - max() and min() in this class.

Implement the two methods using the following guidelines:


Testing the utilities
Now we'll build a program that tests the utilities.

You can copy the the form from "Readinput03" or create e new form from scratch. If you copy from "Readinput03" you must remember to adapt the labels and maybe also names of some of the components.

Your form should look something like this:

     

The code associated with click on the button should do the following:

If you used -2 and 14 as input the window should look something like:
     

Checking for no input (optional)
Before we move on we'd like to be able to check whether the user actually entered any input in the two text-fields.

Remember that we store the result from the text-fields in Strings using the getText() method?
So what we would like to do is to check whether these strings are empty or not.
To check the value of a String we use the method equals() defined in the String class:

Assume we have the following declaration: String myString;
If the string is empty then myString.equals("") will return true (and otherwise false)

If they are empty it would be a mistake to perform the parseInt() (there is nothing to parse from).

Please note that another mistake could be that the strings actually do have a value, but it is not expressing an int value (like "Hi 123"). In that case the parseInt() method will show error-messages in the NetBeans Output area - later we'll learn how to solve this problem more elegantly.


Extending to three input values
Now we'll extend the utility class.

The form should be changed so it can test these new methods as well:

In the method associated with click on the button you should now do the following:


Maintained by: Allan Helboe
Updated: 28 November, 2007 15:57