Build a GUI to accept integers (when the ENTER key is depressed) into an arr ay of 15 int; have a button called AVERAGE; when AVERAGE is selected, there is a display of the count and the current average; have a button called CLEA R; when CLEAR is selected, count is set to 0 and so are all the array elemen ts and then there is another display: count is 0 and average is 0.0.
//----------------------------------------------------------------- // Constructor: Sets up the main GUI components. //----------------------------------------------------------------- public ArrayGUIPanel() {
count = 0; avg=0.0;
inputLabel = new JLabel ("Enter integers: " ); resultLabel = new JLabel ("---"); countLabel = new JLabel ("Count: " + count); averageLabel = new JLabel ("Average: " + avg);
average = new JButton ("AVERAGE"); clear = new JButton ("CLEAR");
AvgListener listener = new AvgListener(); average.addActionListener (listener); clear.addActionListener(listener);
Looks good to me. You didn't use any Layout Manager, but that's no error.
Hint: If you'r using Java 1.5 you may consider to use java.util.ArrayList<Integer> instead of int[] to store your numbers. There are two advantages: 1. You can drop the counter. Use list.size() for the number of entries 2. You can enter as much values as you want
The disadvantage is that you can't create ArrayList<int>, but must use ArrayList<Integer> instead. That means, that you add a new entry like this:
list.add(15);//using Java1.5's autoboxing
or
list.add(new Integer(15));//that's how the autoboxing feuture changes your code
and get the value like this:
list.get(2).intValue();
Hint: Make surea that you cast your sum from int to double before dividing.
Hint: You can also use a JFormattedTextField instead of JTextField . This way you can make sure the user types a number and not text. If you use a JTextfield you have to parse the entry, catch the NumerFormatException ... Using the JTextfield you can set it to accept only numbers and to ignore everything else (returns to it's previous value).
Hint: If you're using the ArrayList instead of the array, you can use the for-each feature of Java 1.5. That's a cool feature which makes code much more easier to read. It would also work for a array, but would ainclude all entries from that array, no matter how many are actually valid.