|
Java Tutorial |
MoreClassesThese pages make up the course notes for my Java programming course (run at Dallam, Milnthorpe, Cumbria). Hopefully they also make a useful self-learning tutorial. More classes In the last section we looked at adding more methods to the VatBill class. One reason for splitting things up into methods is to allow the same block of code to be used many times without typing it (or copying and pasting it) over and over. At first there may seem to be little difference but, significantly, if you make a mistake, and then copy and paste that mistake many times, you will have to find and fix every occurrence of that mistake. This approach also applies to classes. Most Programs are made up of many classes, in fact you have been using some classes provided as standard with the Java Development Kit. If you look back at the list of words that make up the Java language (see IntroductionToProgramming), you will not find String or System, yet we have been using these – because they are classes that someone else wrote, and provided to you as part of Java. Considering our VatBill class, at the moment we have to edit the code to change the item amounts; it would be nice if we could prompt the user to type in the amounts. We could implement all this in the VatBill class but thinking ahead, there may be other occasions when we want to prompt the user to enter a value, so it is worth creating a general purpose class that we can use to do this. Here’s how Create a new class, in EasyEclipse select File -> New -> Class and in the dialog that comes up give the class a name of InputPopUp . Ignore any warnings about the default package (more about this in ClassesInDetail) and click Finish. Paste the following into the InputPopUp class, replacing anything that is there.
import javax.swing.JOptionPane;
public class InputPopUp {
public static String prompt(String label) {
String inputString="";
boolean inputIsValid=false;
Integer exampleInteger=0;
/* The actual dialog box. Data entered is returned
as a string and assigned to inputString.*/
inputString = JOptionPane.showInputDialog(label);
return inputString;
}
public static void display(Object message, String title) {
//Now we can use our data! Example:
JOptionPane.showMessageDialog(null, message, title,
JOptionPane.INFORMATION_MESSAGE);
}
}
This class has two methods, the first called prompt creates a little window with an input box. The second called display creates a window to display a message. Having created this we need to modify the VatBill class to make use of it. Let’s start with something fairly simple and build it up. Initially we will just prompt the user for a value and then do the calculation and display the result. Currently this line sets up the values at the top of the main method. Replace it with This declares the items variable without assigning any values (in this case all the values in the array will be zero). We can now use the InputPopUp class to prompt the user for a value. To refer to the InputPopUp we just use its name and to access a method of the InputPopUp class we put a dot, followed by the method name: That’s fine but we need to know the value the user entered. Take a look at the InputPopUp.prompt method, you will see that it returns a String so we can get that String back into a local variable: Now we have a bit of an issue, we want a float, but we have a String. As far as we are concerned the two things look the same, but to the computer they are completely different. To change the String to a float we need to use the Float class (notice the upper case first letter). As an aside, all the “primitive types” (int, long, float, double, char) have corresponding classes (Integer, Long, Float, Double, Character) which have useful methods for converting, formatting etc. Enter this as the next line This converts the contents of the
public static void main(String[] args) {
float[] items = new float[3];
//prompt for a value
String sValue = InputPopUp.prompt("Enter a value");
items[0] = Float.parseFloat(sValue);
//add up the items to get the net price
int count;
float netPrice = 0;
for (count=0; count<3; count=count+1) {
...
Now it would be better if we could collect a number of values from the user, and add these up. So we need some way of prompting the user repeatedly and get each value. We could collect the values into an array, like we have been doing, but we do not know how many values the user will enter, so instead it may be better to keep a running total. We also need a way to know that the user has finished entering values. Look at how our class works and consider how you might achieve this. What I have decided to do it to replace the for loop with a different type of loop –
public static void main(String[] args) {
//add up the items to get the net price
int count;
float netPrice = 0;
String sValue;
do {
sValue = InputPopUp.prompt("Enter a value");
netPrice = netPrice + Float.parseFloat(sValue);
} while (sValue != null);
display("The net price is " + netPrice);
// give a 10% discount on amounts more than £20.00
if (netPrice > 20) {
What this code aims to do is: * declare the Try running this code and see what happens Remember the intention is that we add values until the input box is left empty by the user, so enter a value and click Ok and then click Ok without entering a value. It should run until you leave the box empty and then you should see an error in the output: Try running it again but this time enter a value and second time round click cancel. This time you get a different error. Let's think about what has gone wrong. A good way of solving problems like this is to read the code and imagine what will happen at each line (another way is to use the debugger, but for now we should be able to solve this manually). * We enter the do loop and get a value back into the sValue variable. * On the next line we try to convert this to a float . * But what if the sValue variable is empty, or not a number? Look at the error that was generated - java.lang.NumberFormatException? - the clue is in that message. When we leave the inputBox empty, we get back an empty String, which cannot be converted to a number. So we get an error. Java has an in-built mechanism for handling errors and we are going to use it to prevent this problem. The basic syntax is
try {
... do something
}
catch (someException e) {
... do something about the exception which is pointed to
by the variable e
}
We are trying to convert a String to a number and sometimes we get an exception. The part that performs th conversion is For now we will assume that if we can't convert it then we will exit out of the loop. So lets modify the do loop to trap the Exception and exit. The do loop now looks like:
do {
sValue = InputPopUp.prompt("Enter a value");
try {
netPrice = netPrice + Float.parseFloat(sValue);
}
catch (Exception e) {
//force sValue to null to make sure we exit the loop
sValue = null;
}
} while (sValue != null);
Notice that there are a lot of braces { } in there. It is a good idea to indent the code inside the braces so that it is easy to see where the block of code inside the braces begins and ends. Try running this now, it should work. What happens now is that if the conversion of sValue to a number fails we end up inside the catch block. In here we force sValue to be null so that we will exit the loop. The rest of the program is then the same as before. Note This work is Copyright Chris Hunter 2007, you may use it for non-commercial purposes |