|
RHS |
MyUtils
In the class Math you'll find a lot of mathematical functions and utilities that proves extrememly helpful.
In this exercise we'll start building our own class of utilities. We'll start by copying and extending a few of the methods from the Math class, but in the future as you create various methods that might be useful in general you should put a copy of the method in your own toolbox.
Start by creating the project "My utils" in NetBeans, mount a new folder and create a class MyUtils (right-click the folder, choose New -> Java class) .
max(int, int) and min(int, int)
We will start by putting two utilities (max() and min()) in this class that
already exists in the Math class - but soon
we'll extend their usability.
Implement the two methods using the following guidelines:
Testing the utilities
Now we'll build a program that tests the utilities.
Create a form (right-click the folder, choose New -> JFrame
form), place a JPanel component
(give it AbsoluteLayout) at the top.
In the panel place two labels and two text-fields.
Under the panel place a JButton and a JTextArea.
Your form should look something like this:
![]() |
The code associated with click on the button should do the following:
![]() |
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 strObj;
If the string is empty then strObj.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: