Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
COS 312 DAY 13
Tony Gauvin
Agenda
• Questions?
• Assignment 4 Posted & Due Date Postponed
– Chap 6 & 7
– Due April 4 (Monday after Spring Break)
• 2nd Capstone Progress Report Due March 24
• Code and PowerPoint access issues should be fixed
• Finish GUI’s
• Begin Arrays
Ch 1 -2
Chapter 6
Graphical User Interfaces
Chapter Scope
•
•
•
•
•
•
•
GUI components, events, and listeners
Containers
Buttons, text fields, sliders, combo boxes
Layout managers
Mouse and keyboard events
Dialog boxes
Borders, tool tips, and mnemonics
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6-4
Containment Hierarchies
• The way components are grouped into containers,
and the way those containers are nested within each
other, establishes the containment hierarchy for a
GUI
• For any Java GUI program, there is generally one
primary (top-level) container, such as a frame or
applet
• The top-level container often contains one or more
containers, such as panels
• These panels may contain other panels to organize
the other components as desired
• https://docs.oracle.com/javase/tutorial/uiswing/co
mponents/toplevel.html
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6-5
Mouse and Key Events
• In addition to component events, events are also
fired when a user interacts with the computer’s
mouse and keyboard
• Mouse events
– mouse events – occur when the user interacts with another
component via the mouse. To use, implement the MouseListener
interface class
– mouse motion events – occur while the mouse is in motion. To use,
implement the MouseMotionListener interface class
– https://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseLi
stener.html
– https://docs.oracle.com/javase/7/docs/api/java/awt/event/Mouse
MotionListener.html
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6-6
Mouse and Mouse Motion Events
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6-7
Coordinates Example
• Clicking the mouse causes a dot to appear in that
location and the coordinates to be displayed
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6-8
//********************************************************************
// CoordinatesPanel.java
Java Foundations
//
// Represents the primary panel for the Coordinates program.
//********************************************************************
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class CoordinatesPanel extends JPanel
{
private final int SIZE = 6; // diameter of dot
private int x = 50, y = 50;
// coordinates of mouse press
//----------------------------------------------------------------// Constructor: Sets up this panel to listen for mouse events.
//----------------------------------------------------------------public CoordinatesPanel()
{
addMouseListener(new CoordinatesListener());
setBackground(Color.black);
setPreferredSize(new Dimension(300, 200));
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6-9
//----------------------------------------------------------------// Draws all of the dots stored in the list.
//----------------------------------------------------------------public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor(Color.green);
page.fillOval(x, y, SIZE, SIZE);
page.drawString("Coordinates: (" + x + ", " + y + ")", 5, 15);
}
//*****************************************************************
// Represents the listener for mouse events.
//*****************************************************************
private class CoordinatesListener implements MouseListener
{
//-------------------------------------------------------------// Adds the current point to the list of points and redraws
// the panel whenever the mouse button is pressed.
//-------------------------------------------------------------public void mousePressed(MouseEvent event)
{
x = event.getX();
y = event.getY();
repaint();
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 10
//-------------------------------------------------------------// Provide empty definitions for unused event methods.
//-------------------------------------------------------------public void mouseClicked(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
}
}
Code\chap6\CoordinatesPanel.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 11
//********************************************************************
// Coordinates.java
Java Foundations
//
// Demonstrates mouse events.
//********************************************************************
import javax.swing.JFrame;
public class Coordinates
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main(String[] args)
{
JFrame frame = new JFrame("Coordinates");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CoordinatesPanel());
frame.pack();
frame.setVisible(true);
}
}
Code\chap6\Coordinates.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 12
Coordinates Example
• The event object passed to the listener is used to
get the coordinates of the event (its been
ignored in previous examples)
• Unused methods of the MouseListener
interface are given empty methods
– Must implement all methods of an interface
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 13
RubberLines Example
• As the mouse is dragged, the line is redrawn
• This creates a rubberbanding effect, as if the line
is being pulled into shape
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 14
RubberLines Example
• This example uses both mouse and mouse
motion events
• The initial click is captured using the mouse
pressed event
• Then the line is updated continually using the
mouse dragged event
– Uses Java Class Point ( x, y)
– http://docs.oracle.com/javase/7/docs/api/java/awt/P
oint.html
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 15
//********************************************************************
// RubberLinesPanel.java
Java Foundations
//
// Represents the primary drawing panel for the RubberLines program.
//********************************************************************
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class RubberLinesPanel extends JPanel
{
private Point point1 = null, point2 = null;
//----------------------------------------------------------------// Constructor: Sets up this panel to listen for mouse events.
//----------------------------------------------------------------public RubberLinesPanel()
{
LineListener listener = new LineListener();
addMouseListener(listener);
addMouseMotionListener(listener);
setBackground(Color.black);
setPreferredSize(new Dimension(400, 200));
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 16
//----------------------------------------------------------------// Draws the current line from the intial mouse-pressed point to
// the current position of the mouse.
//----------------------------------------------------------------public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor (Color.yellow);
if (point1 != null && point2 != null)
page.drawLine(point1.x, point1.y, point2.x, point2.y);
}
//*****************************************************************
// Represents the listener for all mouse events.
//*****************************************************************
private class LineListener implements MouseListener,
MouseMotionListener
{
//-------------------------------------------------------------// Captures the initial position at which the mouse button is
// pressed.
//-------------------------------------------------------------public void mousePressed(MouseEvent event)
{
point1 = event.getPoint();
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 17
//-------------------------------------------------------------// Gets the current position of the mouse as it is dragged and
// redraws the line to create the rubberband effect.
//-------------------------------------------------------------public void mouseDragged(MouseEvent event)
{
point2 = event.getPoint();
repaint();
}
//-------------------------------------------------------------// Provide empty definitions for unused event methods.
//-------------------------------------------------------------public void mouseClicked(MouseEvent event) {}
public void mouseReleased(MouseEvent event) {}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mouseMoved(MouseEvent event) {}
}
}
Code\chap6\RubberLinesPanel.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 18
//********************************************************************
// RubberLines.java
Java Foundations
//
// Demonstrates mouse events and rubberbanding.
//********************************************************************
import javax.swing.JFrame;
public class RubberLines
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main(String[] args)
{
JFrame frame = new JFrame("Rubber Lines");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RubberLinesPanel());
frame.pack();
frame.setVisible(true);
}
}
Code\chap6\RubberLines.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 19
Key Events
• A key event is generated when the user presses a
keyboard key
• This allows a program to respond immediately to
the user while they are typing
• The KeyListener interface defines three methods
used to respond to keyboard activity
http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 20
Direction Example
• As the user presses the arrow keys on the
keyboard, an arrow image is displayed and
moved in the appropriate direction
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 21
//********************************************************************
// DirectionPanel.java
Java Foundations
//
// Represents the primary display panel for the Direction program.
//********************************************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DirectionPanel extends JPanel
{
private final int WIDTH = 300, HEIGHT = 200;
private final int JUMP = 10; // increment for image movement
private final int IMAGE_SIZE = 31;
private ImageIcon up, down, right, left, currentImage;
private int x, y;
//----------------------------------------------------------------// Constructor: Sets up this panel and loads the images.
//----------------------------------------------------------------public DirectionPanel()
{
addKeyListener (new DirectionListener());
x = WIDTH / 2;
y = HEIGHT / 2;
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 22
up = new ImageIcon("arrowUp.gif");
down = new ImageIcon("arrowDown.gif");
left = new ImageIcon("arrowLeft.gif");
right = new ImageIcon("arrowRight.gif");
currentImage = right;
setBackground(Color.black);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
}
//----------------------------------------------------------------// Draws the image in the current location.
//----------------------------------------------------------------public void paintComponent(Graphics page)
{
super.paintComponent(page);
currentImage.paintIcon(this, page, x, y);
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 23
//*****************************************************************
// Represents the listener for keyboard activity.
//*****************************************************************
private class DirectionListener implements KeyListener
{
//-------------------------------------------------------------// Responds to the user pressing arrow keys by adjusting the
// image and image location accordingly.
//-------------------------------------------------------------public void keyPressed(KeyEvent event)
{
switch (event.getKeyCode())
{
case KeyEvent.VK_UP:
currentImage = up;
y -= JUMP;
break;
case KeyEvent.VK_DOWN:
currentImage = down;
y += JUMP;
break;
case KeyEvent.VK_LEFT:
currentImage = left;
x -= JUMP;
break;
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 24
case KeyEvent.VK_RIGHT:
currentImage = right;
x += JUMP;
break;
}
repaint();
}
//-------------------------------------------------------------// Provide empty definitions for unused event methods.
//-------------------------------------------------------------public void keyTyped(KeyEvent event) {}
public void keyReleased(KeyEvent event) {}
}
}
Code\chap6\DirectionPanel.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 25
//********************************************************************
// Direction.java
Java Foundations
//
// Demonstrates key events.
//********************************************************************
import javax.swing.JFrame;
public class Direction
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main(String[] args)
{
JFrame frame = new JFrame("Direction");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DirectionPanel());
frame.pack();
frame.setVisible(true);
}
}
Code\chap6\Direction.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 26
Extending Adapter Classes
• In our previous examples, we’ve created the
listener classes by implementing a particular
listener interface
• An alternative technique for creating a listener
class is to use inheritance and extend an adapter
class
• Each listener interface that contains more than
one method has a corresponding adapter class
containing empty definitions for all methods in
the interface
• We can override any event methods we need in
our new child class
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 27
Extending Adapter Classes
• For example:
– The MouseAdapter class implements the MouseListener
interface class and provides empty method definitions for the
five mouse event methods
– By subclassing (inherit or extend) MouseAdapter, we can
avoid implementing the interface directly
• This approach can save coding time and keep
source code easier to read
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 28
Direction panel using adapters
• Same functionality but less code to write
– Code\chap6\DirectionPanelAdapters.java
– Code\chap6\DirectionAdapter.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
5 - 29
Dialog Boxes
• A dialog box is a graphical window that pops up
on top of any currently active window so that the
user can interact with it
• A dialog box can serve a variety of purposes
– conveying information
– confirming an action
– permitting the user to enter information
• The JOptionPane class simplifies the creation and
use of basic dialog boxes
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 30
Dialog Boxes
• JOptionPane dialog
boxes fall into three
categories
– message dialog boxes – used to display an output string
– input dialog boxes – presents a prompt and a single input txt
field into which the user can enter one string of data
– confirm dialog box – presents the user with a simple yes-or-no
question
• These three types of dialog boxes are created
using static methods in the JOptionPane class
• Many of the JOptionPane methods allow the
program to tailor the contents of the dialog box
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 31
JOptionPane Methods
http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 32
EvenOdd Example
• Determines if an integer is even or odd
• Instead of a single frame, it uses three dialog
boxes
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 33
//********************************************************************
// EvenOdd.java
Java Foundations
//
// Demonstrates the use of the JOptionPane class.
//********************************************************************
import javax.swing.JOptionPane;
public class EvenOdd
{
//----------------------------------------------------------------// Determines if the value input by the user is even or odd.
// Uses multiple dialog boxes for user interaction.
//----------------------------------------------------------------public static void main(String[] args)
{
String numStr, result;
int num, again;
do
{
numStr = JOptionPane.showInputDialog("Enter an integer: ");
num = Integer.parseInt(numStr);
result = "That number is " + ((num%2 == 0) ? "even" : "odd");
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 34
JOptionPane.showMessageDialog(null, result);
again = JOptionPane.showConfirmDialog(null, "Do Another?");
}
while (again == JOptionPane.YES_OPTION);
}
}
Code\chap6\EvenOdd.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 35
File Choosers
• A file chooser is a specialized
dialog box used to select a file
from a disk or other storage
medium
• The dialog automatically
presents a standardized file
selection window
• Filters can be applied to the
file chooser programmatically
• The JFileChooser class
creates this type of dialog box
• http://docs.oracle.com/javase
/7/docs/api/javax/swing/JFile
Chooser.html
1-36
//********************************************************************
// DisplayFile.java
Java Foundations
//
// Demonstrates the use of a file chooser and a text area.
//********************************************************************
import java.util.Scanner;
import java.io.*;
import javax.swing.*;
public class DisplayFile
{
//----------------------------------------------------------------// Opens a file chooser dialog, reads the selected file and
// loads it into a text area.
//----------------------------------------------------------------public static void main(String[] args) throws IOException
{
JFrame frame = new JFrame("Display File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea ta = new JTextArea(20, 30);
JFileChooser chooser = new JFileChooser();
int status = chooser.showOpenDialog(null);
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 37
if (status != JFileChooser.APPROVE_OPTION)
ta.setText("No File Chosen");
else
{
File file = chooser.getSelectedFile();
Scanner scan = new Scanner(file);
String info = "";
while (scan.hasNext())
info += scan.nextLine() + "\n";
ta.setText(info);
}
frame.getContentPane().add(ta);
frame.pack();
frame.setVisible(true);
}
}
Code\chap6\DisplayFile.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 38
Color Choosers
• A color chooser dialog box can
be displayed, permitting the
user to select color from a list
• The JColorChooser
represents a color chooser
dialog box
• The user can also specify a
color using RGB values
• http://docs.oracle.com/javase
/7/docs/api/javax/swing/JColo
rChooser.html
• Code\chap6\DisplayColor.java
1-39
Borders
• Java provides the ability to put a border around any
Swing component
• A border is not a component but defines how the
edge of a component should be drawn
• Border provide visual cues as to how GUI
components are organized
• The BorderFactory class is useful for creating borders
for components
• http://docs.oracle.com/javase/7/docs/api/javax/swi
ng/BorderFactory.html
• https://docs.oracle.com/javase/tutorial/uiswing/co
mponents/border.html
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 40
Borders
• Some borders that can be defined using the
BorderFactory class:
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 41
BorderDemo Example
• Displays several small panels with various
borders
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 42
//********************************************************************
// BorderDemo.java
Java Foundations
//
// Demonstrates the use of various types of borders.
//********************************************************************
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderDemo
{
//----------------------------------------------------------------// Creates several bordered panels and displays them.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame("Border Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 5, 10));
panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
JPanel p1 = new JPanel();
p1.setBorder(BorderFactory.createLineBorder(Color.red, 3));
p1.add(new JLabel("Line Border"));
panel.add(p1);
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 43
JPanel p2 = new JPanel();
p2.setBorder(BorderFactory.createEtchedBorder());
p2.add(new JLabel("Etched Border"));
panel.add(p2);
JPanel p3 = new JPanel();
p3.setBorder(BorderFactory.createRaisedBevelBorder());
p3.add(new JLabel("Raised Bevel Border"));
panel.add(p3);
JPanel p4 = new JPanel();
p4.setBorder(BorderFactory.createLoweredBevelBorder());
p4.add(new JLabel("Lowered Bevel Border"));
panel.add(p4);
JPanel p5 = new JPanel();
p5.setBorder(BorderFactory.createTitledBorder("Title"));
p5.add(new JLabel("Titled Border"));
panel.add(p5);
JPanel p6 = new JPanel();
TitledBorder tb = BorderFactory.createTitledBorder("Title");
tb.setTitleJustification(TitledBorder.RIGHT);
p6.setBorder(tb);
p6.add(new JLabel("Titled Border (right)"));
panel.add (p6);
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 44
JPanel p7 = new JPanel();
Border b1 = BorderFactory.createLineBorder(Color.blue, 2);
Border b2 = BorderFactory.createEtchedBorder();
p7.setBorder (BorderFactory.createCompoundBorder(b1, b2));
p7.add (new JLabel("Compound Border"));
panel.add(p7);
JPanel p8 = new JPanel();
Border mb = BorderFactory.createMatteBorder(1, 5, 1, 1,
Color.red);
p8.setBorder(mb);
p8.add(new JLabel("Matte Border"));
panel.add(p8);
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
}
}
Code\chap6\BorderDemo.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 45
Tool Tips
• A tool tip is a short line of text that appears over
a component when the mouse cursor is rested
momentarily on top of the component
• Tool tips usually inform the user about the
component
• Tool tips can be assigned by using the
setToolTipText method of a component
JButton button = new Button(“Compute”);
button.setToolTipText(“Calculates the area under the curve”);
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 46
Mnemonics
• A mnemonic is a character that allows the user to push a
button or make a menu choice using the keyboard in
addition to the mouse
• For example, when a mnemonic has been defined for a
button, the user can hold down the Alt key and press
the mnemonic character to activate (depress) the button
• We set the mnemonic for a component using the
setMnemonic method of the component
• A character in the label may be underlined to indicate
that it can be used as a shortcut
1-47
Disabling Components
• A component can be disabled to indicate it
should not (cannot) be used
• A disabled component is usually "greyed out"
• This helps guide the user
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 48
LightBulb Example
• Tool tips, mnemonics, and disabled components
are used in this example
• It displays an "on" or "off" bulb depending on
which button is pressed
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 49
//********************************************************************
// LightBulb.java
Java Foundations
//
// Demonstrates mnemonics and tool tips.
//********************************************************************
import javax.swing.*;
import java.awt.*;
public class LightBulb
{
//----------------------------------------------------------------// Sets up a frame that displays a light bulb image that can be
// turned on and off.
//----------------------------------------------------------------public static void main(String[] args)
{
JFrame frame = new JFrame("Light Bulb");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LightBulbPanel bulb = new LightBulbPanel();
LightBulbControls controls = new LightBulbControls (bulb);
JPanel panel = new JPanel();
panel.setBackground(Color.black);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 50
panel.add(Box.createRigidArea (new Dimension (0, 20)));
panel.add(bulb);
panel.add(Box.createRigidArea (new Dimension (0, 10)));
panel.add(controls);
panel.add(Box.createRigidArea (new Dimension (0, 10)));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Code\chap6\LightBulb.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 51
//********************************************************************
// LightBulbPanel.java
Java Foundations
//
// Represents the image for the LightBulb program.
//********************************************************************
import javax.swing.*;
import java.awt.*;
public class LightBulbPanel extends JPanel
{
private boolean on;
private ImageIcon lightOn, lightOff;
private JLabel imageLabel;
//----------------------------------------------------------------// Constructor: Sets up the images and the initial state.
//----------------------------------------------------------------public LightBulbPanel()
{
lightOn = new ImageIcon("lightBulbOn.gif");
lightOff = new ImageIcon("lightBulbOff.gif");
setBackground(Color.black);
on = true;
imageLabel = new JLabel(lightOff);
add(imageLabel);
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 52
//----------------------------------------------------------------// Paints the panel using the appropriate image.
//----------------------------------------------------------------public void paintComponent(Graphics page)
{
super.paintComponent(page);
if (on)
imageLabel.setIcon(lightOn);
else
imageLabel.setIcon(lightOff);
}
//----------------------------------------------------------------// Sets the status of the light bulb.
//----------------------------------------------------------------public void setOn(boolean lightBulbOn)
{
on = lightBulbOn;
}
}
Code\chap6\LightBulbPanel.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 53
//********************************************************************
// LightBulbControls.java
Java Foundations
//
// Represents the control panel for the LightBulb program.
//********************************************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LightBulbControls extends JPanel
{
private LightBulbPanel bulb;
private JButton onButton, offButton;
//----------------------------------------------------------------// Sets up the lightbulb control panel.
//----------------------------------------------------------------public LightBulbControls(LightBulbPanel bulbPanel)
{
bulb = bulbPanel;
onButton = new JButton("On");
onButton.setEnabled(false);
onButton.setMnemonic('n');
onButton.setToolTipText("Turn it on!");
onButton.addActionListener(new OnListener());
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 54
offButton = new JButton("Off");
offButton.setEnabled(true);
offButton.setMnemonic('f');
offButton.setToolTipText("Turn it off!");
offButton.addActionListener(new OffListener());
setBackground(Color.black);
add(onButton);
add(offButton);
}
//*****************************************************************
// Represents the listener for the On button.
//*****************************************************************
private class OnListener implements ActionListener
{
//-------------------------------------------------------------// Turns the bulb on and repaints the bulb panel.
//-------------------------------------------------------------public void actionPerformed(ActionEvent event)
{
bulb.setOn(true);
onButton.setEnabled(false);
offButton.setEnabled(true);
bulb.repaint();
}
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 55
//*****************************************************************
// Represents the listener for the Off button.
//*****************************************************************
private class OffListener implements ActionListener
{
//-------------------------------------------------------------// Turns the bulb off and repaints the bulb panel.
//-------------------------------------------------------------public void actionPerformed(ActionEvent event)
{
bulb.setOn(false);
onButton.setEnabled(true);
offButton.setEnabled(false);
bulb.repaint();
}
}
}
Code\chap6\LightBulbControls.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 56
GUI Design
• Keep in mind our goal is to solve a problem
• Fundamental ideas of good GUI design include
–
–
–
–
knowing the user
preventing user errors
optimizing user abilities
being consistent
• We should design interfaces so that the user can
make as few mistakes as possible
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
6 - 57
Chapter 7
Arrays
Chapter Scope
•
•
•
•
•
•
•
Array declaration and use
Bounds checking
Arrays as objects
Arrays of objects
Command-line arguments
Variable-length parameter lists
Multidimensional arrays
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 59
Abstract Data Structures in JAVA
• Queues
– Stacks
• Lists
– Arrays
– Linked list
– Sets
• Trees
– Binary trees
– B-trees
– Red-black trees
• Hash Tables
• Heaps
• Maps
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
5 - 60
Arrays
• An array is an ordered list of values
The entire array
has a single name
0
scores
Each value has a numeric index
1
2
3
4
5
6
7
8
9
79 87 94 82 67 98 87 81 74 91
An array of size N is indexed from zero to N-1
This array holds 10 values that are indexed from 0 to 9
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 61
Arrays
• A particular value in an array is referenced using
the array name followed by the index in brackets
• For example, the expression
scores[2]
refers to the value 94 (the 3rd value in the array)
• That expression represents a place to store a
single integer and can be used wherever an
integer variable can be used
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 62
Arrays
• Arrays can be depicted vertically or horizontally
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 63
Arrays
• An array element can be assigned a value, printed,
or used in a calculation
scores[2] = 89;
scores[first] = scores[first] + 2;
mean = (scores[0] + scores[1])/2;
System.out.println("Top = " + scores[5]);
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 64
Arrays
• The values held in an array are called array elements
• An array stores multiple values of the same type –
the element type
• The element type can be a primitive type or an
object reference
• Therefore, we can create an array of integers, an
array of characters, an array of String objects, an
array of Coin objects, etc.
• In Java, the array itself is an object that must be
instantiated
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 65
Declaring Arrays
• The scores array could be declared as follows
int[] scores = new int[10];
• The type of the variable scores is int[] (an array
of integers)
• Note that the array type does not specify its size,
but each object of that type has a specific size
• The reference variable scores is set to a new array
object that can hold 10 integers
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 66
Declaring Arrays
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 67
Declaring Arrays
• Some other examples of array declarations
float[] prices = new float[500];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 68
Using Arrays
• The for-each loop can be used when processing
array elements:
for (int score : scores)
System.out.println(score);
• This is only appropriate when processing all array
elements from the lowest index to the highest
index
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 69
//********************************************************************
// BasicArray.java
Java Foundations
//
// Demonstrates basic array declaration and use.
//********************************************************************
public class BasicArray
{
//----------------------------------------------------------------// Creates an array, fills it with various integer values,
// modifies one value, then prints them out.
//----------------------------------------------------------------public static void main(String[] args)
{
final int LIMIT = 15, MULTIPLE = 10;
int[] list = new int[LIMIT];
// Initialize the array values
for (int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;
list[5] = 999;
// change one array value
// Print the array values
for (int value : list)
System.out.print(value + "
");
}
}
Code\chap7\BasicArray.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 70
BasicArray Example
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 71
Bounds Checking
• Once an array is created, it has a fixed size
• An index used in an array reference must specify
a valid element
• That is, the index value must be in range 0 to N-1
• The Java interpreter throws an
ArrayIndexOutOfBoundsException
if an array
index is out of bounds
• This is called automatic bounds checking
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 72
Bounds Checking
• For example, if the array codes can hold 100 values,
it can be indexed using only the numbers 0 to 99
• If the value of count is 100, then the following
reference will cause an exception to be thrown
System.out.println(codes[count]);
• It’s common to introduce off-by-one errors when
using arrays
problem
for (int index=0; index <= 100; index++)
codes[index] = index*50 + epsilon;
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 73
Bounds Checking
• Each array object has a public constant called
length that stores the size of the array
• It is referenced using the array name
scores.length
• Note that length holds the number of
elements, not the largest index
– Largest index is always (length – 1)
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 74
//********************************************************************
// ReverseOrder.java
Java Foundations
//
// Demonstrates array index processing.
//********************************************************************
import java.util.Scanner;
public class ReverseOrder
{
//----------------------------------------------------------------// Reads a list of numbers from the user, storing them in an
// array, then prints them in the opposite order.
//----------------------------------------------------------------public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
double[] numbers = new double[10];
System.out.println("The size of the array: " + numbers.length);
for (int index = 0; index < numbers.length; index++)
{
System.out.print("Enter number " + (index+1) + ": ");
numbers[index] = scan.nextDouble();
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 75
System.out.println("The numbers in reverse order:");
for (int index = numbers.length-1; index >= 0; index--)
System.out.print(numbers[index] + " ");
}
}
Code\chap7\ReverseOrder.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 76
//********************************************************************
// LetterCount.java
Java Foundations
//
// Demonstrates the relationship between arrays and strings.
//********************************************************************
import java.util.Scanner;
public class LetterCount
{
//----------------------------------------------------------------// Reads a sentence from the user and counts the number of
// uppercase and lowercase letters contained in it.
//----------------------------------------------------------------public static void main(String[] args)
{
final int NUMCHARS = 26;
Scanner scan = new Scanner(System.in);
int[] upper = new int[NUMCHARS];
int[] lower = new int[NUMCHARS];
char current;
int other = 0;
// the current character being processed
// counter for non-alphabetics
System.out.println("Enter a sentence:");
String line = scan.nextLine();
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 77
// Count the number of each letter occurrence
for (int ch = 0; ch < line.length(); ch++)
{
current = line.charAt(ch);
if (current >= 'A' && current <= 'Z')
upper[current-'A']++;
else
if (current >= 'a' && current <= 'z')
lower[current-'a']++;
else
other++;
}
// Print the results
System.out.println ();
for (int letter=0; letter < upper.length; letter++)
{
System.out.print((char) (letter + 'A'));
System.out.print(": " + upper[letter]);
System.out.print("\t\t" + (char) (letter + 'a'));
System.out.println(": " + lower[letter]);
}
System.out.println();
System.out.println("Non-alphabetic characters: " + other);
}
}
Code\chap7\LetterCount.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 78
Alternate Array Syntax
• The brackets of the array type can be associated
with the element type or with the name of the array
• Therefore the following two declarations are
equivalent
float[] prices;
float prices[];
HIGHLY Discouraged
• The first format generally is more readable and
should be used
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 79
Initializer Lists
• An initializer list can be used to instantiate and fill
an array in one step
• The values are delimited by braces and separated
by commas
• Examples:
int[] units = {147, 323, 89, 933, 540,
269, 97, 114, 298, 476};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 80
Initializer Lists
• Note that when an initializer list is used
– the new operator is not used
– no size value is specified (or needed)
• The size of the array is determined by the
number of items in the initializer list
• An initializer list can be used only in the array
declaration
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 81
//********************************************************************
// Primes.java
Java Foundations
//
// Demonstrates the use of an initializer list for an array.
//********************************************************************
public class Primes
{
//----------------------------------------------------------------// Stores some prime numbers in an array and prints them.
//----------------------------------------------------------------public static void main(String[] args)
{
int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
System.out.println("Array length: " + primeNums.length);
System.out.println("The first few prime numbers are:");
for (int prime : primeNums)
System.out.print(prime + "
");
}
}
Code\chap7\Primes.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 82
Arrays as Parameters
• An entire array can be passed as a parameter to a
method
• Like any other object, the reference to the array is
passed, making the formal and actual parameters
aliases of each other
• Therefore, changing an array element within the
method changes the original
• An individual array element can be passed to a
method as well, in which case the type of the formal
parameter is the same as the element type
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 83
Arrays of Objects
• An array is an object and an array can hold
objects as elements
• The array name is an object reference variable
• So this is another way to depict an array:
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 84
Arrays of Objects
• An array of objects really holds object references
• The following declaration reserves space to store
5 references to String objects
String[] words = new String[5];
• It does not create the String objects themselves
• Initially an array of objects holds null references
• Each object stored in an array must be
instantiated separately
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 85
Arrays of Objects
• After initial creation, an array holds null
references:
• Each element is a reference to an object:
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 86
Arrays of Objects
• Keep in mind that String objects can be created
using literals
• The following declaration creates an array object
called verbs and fills it with four String objects
created using string literals
String[] verbs = {"play", "work", "eat", "sleep"};
• The following example creates an array of Grade
objects, each with a string representation and a
numeric lower bound
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 87
//********************************************************************
// Grade.java
Java Foundations
//
// Represents a school grade.
//********************************************************************
public class Grade
{
private String name;
private int lowerBound;
//----------------------------------------------------------------// Constructor: Sets up this Grade object with the specified
// grade name and numeric lower bound.
//----------------------------------------------------------------public Grade(String grade, int cutoff)
{
name = grade;
lowerBound = cutoff;
}
//----------------------------------------------------------------// Returns a string representation of this grade.
//----------------------------------------------------------------public String toString()
{
return name + "\t" + lowerBound;
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 88
//----------------------------------------------------------------// Name mutator.
//----------------------------------------------------------------public void setName(String grade)
{
name = grade;
}
//----------------------------------------------------------------// Lower bound mutator.
//----------------------------------------------------------------public void setLowerBound(int cutoff)
{
lowerBound = cutoff;
}
//----------------------------------------------------------------// Name accessor.
//----------------------------------------------------------------public String getName()
{
return name;
}
//----------------------------------------------------------------// Lower bound accessor.
//----------------------------------------------------------------public int getLowerBound()
{
return lowerBound;
}
}
Code\chap7\Grade.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 89
//********************************************************************
// GradeRange.java
Java Foundations
//
// Demonstrates the use of an array of objects.
//********************************************************************
public class GradeRange
{
//----------------------------------------------------------------// Creates an array of Grade objects and prints them.
//----------------------------------------------------------------public static void main(String[] args)
{
Grade[] grades =
{
new Grade("A", 95), new Grade("A-", 90),
new Grade("B+", 87), new Grade("B", 85), new Grade("B-", 80),
new Grade("C+", 77), new Grade("C", 75), new Grade("C-", 70),
new Grade("D+", 67), new Grade("D", 65), new Grade("D-", 60),
new Grade("F", 0)
};
for (Grade letterGrade : grades)
System.out.println(letterGrade);
}
}
Code\chap7\GradeRange.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 90
Arrays of Objects
• Now let's look at an example that stores a
collection of CD objects
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 91
//********************************************************************
// CD.java
Java Foundations
//
// Represents a compact disc.
//********************************************************************
import java.text.NumberFormat;
public class CD
{
private String title, artist;
private double cost;
private int tracks;
//----------------------------------------------------------------// Creates a new CD with the specified information.
//----------------------------------------------------------------public CD(String name, String singer, double price, int numTracks)
{
title = name;
artist = singer;
cost = price;
tracks = numTracks;
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 92
//----------------------------------------------------------------// Returns a string description of this CD.
//----------------------------------------------------------------public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(cost) + "\t" + tracks + "\t";
description += title + "\t" + artist;
return description;
}
}
Code\chap7\CD.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 93
//********************************************************************
// CDCollection.java
Java Foundations
//
// Represents a collection of compact discs.
//********************************************************************
import java.text.NumberFormat;
public class CDCollection
{
private CD[] collection;
private int count;
private double totalCost;
//----------------------------------------------------------------// Constructor: Creates an initially empty collection.
//----------------------------------------------------------------public CDCollection()
{
collection = new CD[100];
count = 0;
totalCost = 0.0;
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 94
//----------------------------------------------------------------// Adds a CD to the collection, increasing the size of the
// collection if necessary.
//----------------------------------------------------------------public void addCD(String title, String artist, double cost,
int tracks)
{
if (count == collection.length)
increaseSize();
collection[count] = new CD(title, artist, cost, tracks);
totalCost += cost;
count++;
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 95
//----------------------------------------------------------------// Returns a report describing the CD collection.
//----------------------------------------------------------------public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
report += "My CD Collection\n\n";
report += "Number of CDs: " + count + "\n";
report += "Total cost: " + fmt.format(totalCost) + "\n";
report += "Average cost: " + fmt.format(totalCost/count);
report += "\n\nCD List:\n\n";
for (int cd = 0; cd < count; cd++)
report += collection[cd].toString() + "\n";
return report;
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 96
//----------------------------------------------------------------// Increases the capacity of the collection by creating a
// larger array and copying the existing collection into it.
//----------------------------------------------------------------private void increaseSize()
{
CD[] temp = new CD[collection.length * 2];
for (int cd = 0; cd < collection.length; cd++)
temp[cd] = collection[cd];
collection = temp;
}
}
Code\chap7\CDCollection.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 97
//********************************************************************
// Tunes.java
Java Foundations
//
// Demonstrates the use of an array of objects.
//********************************************************************
public class Tunes
{
//----------------------------------------------------------------// Creates a CDCollection object and adds some CDs to it. Prints
// reports on the status of the collection.
//----------------------------------------------------------------public static void main (String[] args)
{
CDCollection music = new CDCollection ();
music.addCD("Storm Front", "Billy Joel", 14.95, 10);
music.addCD("Come On Over", "Shania Twain", 14.95, 16);
music.addCD("Soundtrack", "Les Miserables", 17.95, 33);
music.addCD("Graceland", "Paul Simon", 13.90, 11);
System.out.println(music);
music.addCD("Double Live", "Garth Brooks", 19.99, 26);
music.addCD("Greatest Hits", "Jimmy Buffet", 15.95, 13);
System.out.println(music);
}
}
Code\chap7\Tunes.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 98
Command-Line Arguments
• The signature of the main method indicates that
it takes an array of String objects as a parameter
• These values come from command-line
arguments that are provided when the
interpreter is invoked
• For example, the following invocation of the
interpreter passes three String objects into
main
> java StateEval pennsylvania texas arizona
• These strings are stored at indexes 0-2 of the
array parameter of the main method
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 99
//********************************************************************
// CommandLine.java
Java Foundations
//
// Demonstrates the use of command line arguments.
//********************************************************************
public class CommandLine
{
//----------------------------------------------------------------// Prints all of the command line arguments provided by the
// user.
//----------------------------------------------------------------public static void main(String[] args)
{
for (String arg : args)
System.out.println(arg);
}
}
Code\chap7\CommandLine.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 100
Variable Length Parameter Lists
• Suppose we wanted to create a method that
processed a different amount of data from one
invocation to the next
• For example, let's define a method called average
that returns the average of a set of integer
parameters
// one call to average three values
mean1 = average (42, 69, 37);
// another call to average seven values
mean2 = average (35, 43, 93, 23, 40, 21, 75);
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 101
Variable Length Parameter Lists
• We could define overloaded versions of the
average method
– Downside: we'd need a separate version of the method for
each parameter count
• We could define the method to accept an array
of integers
– Downside: we'd have to create the array and store the integers
prior to calling the method each time
• Instead, Java provides a convenient way to create
variable length parameter lists
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 102
Variable Length Parameter Lists
• Using special syntax in the formal parameter list, we can
define a method to accept any number of parameters of
the same type
• For each call, the parameters are automatically put into
an array for easy processing in the method
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 103
Variable Length Parameter Lists
public double average(int ... list)
{
double result = 0.0;
if (list.length != 0)
{
int sum = 0;
for (int num : list)
sum += num;
result = (double)num / list.length;
}
return result;
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 104
Variable Length Parameter Lists
• The type of the parameter can be any primitive or
object type
public void printGrades(Grade ... grades)
{
for (Grade letterGrade : grades)
System.out.println (letterGrade);
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 105
Variable Length Parameter Lists
• A method that accepts a variable number of
parameters can also accept other parameters
• The following method accepts an int, a String
object, and a variable number of double values into
an array called nums
public void test(int count, String name,
double ... nums)
{
// whatever
}
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 106
Variable Length Parameter Lists
• The varying number of parameters must come
last in the formal arguments
• A single method cannot accept two sets of
varying parameters
• Constructors can also be set up to accept a
variable number of parameters
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 107
//********************************************************************
// Family.java
Java Foundations
//
// Demonstrates the use of variable length parameter lists.
//********************************************************************
public class Family
{
private String[] members;
//----------------------------------------------------------------// Constructor: Sets up this family by storing the (possibly
// multiple) names that are passed in as parameters.
//----------------------------------------------------------------public Family(String ... names)
{
members = names;
}
//----------------------------------------------------------------// Returns a string representation of this family.
//----------------------------------------------------------------public String toString()
{
String result = "";
for (String name : members)
result += name + "\n";
return result;
}
}
Code\chap7\Family.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 108
//********************************************************************
// VariableParameters.java
Java Foundations
//
// Demonstrates the use of a variable length parameter list.
//********************************************************************
public class VariableParameters
{
//----------------------------------------------------------------// Creates two Family objects using a constructor that accepts
// a variable number of String objects as parameters.
//----------------------------------------------------------------public static void main(String[] args)
{
Family lewis = new Family("John", "Sharon", "Justin", "Kayla",
"Nathan", "Samantha");
Family camden = new Family("Stephen", "Annie", "Matt", "Mary",
"Simon", "Lucy", "Ruthie", "Sam", "David");
System.out.println(lewis);
System.out.println();
System.out.println(camden);
}
}
Code\chap7\VariableParameters.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 109
Two-Dimensional Arrays
• A one-dimensional array stores a list of elements
• A two-dimensional array can be thought of as a
table of elements, with rows and columns
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 110
Two-Dimensional Arrays
• To be precise, in Java a two-dimensional array is an
array of arrays
• A two-dimensional array is declared by specifying the
size of each dimension separately
int[][] scores = new int[12][50];
• A array element is referenced using two index values
value = scores[3][6]
• The array stored in one row can be specified using
one index
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 111
//********************************************************************
// TwoDArray.java
Java Foundations
//
// Demonstrates the use of a two-dimensional array.
//********************************************************************
public class TwoDArray
{
//----------------------------------------------------------------// Creates a 2D array of integers, fills it with increasing
// integer values, then prints them out.
//----------------------------------------------------------------public static void main(String[] args)
{
int[][] table = new int[5][10];
// Load the table with values
for (int row=0; row < table.length; row++)
for (int col=0; col < table[row].length; col++)
table[row][col] = row * 10 + col;
// Print the table
for (int row=0; row < table.length; row++)
{
for (int col=0; col < table[row].length; col++)
System.out.print(table[row][col] + "\t");
System.out.println();
}
}
}
Code\chap7\TwoDArray.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 112
Two-Dimensional Arrays
Expression
Type
table
int[][]
table[5]
table[5][12]
int[]
int
Description
2D array of integers, or
array of integer arrays
array of integers
integer
1-113
//********************************************************************
// SodaSurvey.java
Java Foundations
//
// Demonstrates the use of a two-dimensional array.
//********************************************************************
import java.text.DecimalFormat;
public class SodaSurvey
{
//----------------------------------------------------------------// Determines and prints the average of each row (soda) and each
// column (respondent) of the survey scores.
//----------------------------------------------------------------public static void main (String[] args)
{
int[][] scores = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4},
{2, 4, 3, 4, 3, 3, 2, 1, 2, 2},
{3, 5, 4, 5, 5, 3, 2, 5, 5, 5},
{1, 1, 1, 3, 1, 2, 1, 3, 2, 4} };
final int SODAS = scores.length;
final int PEOPLE = scores[0].length;
int[] sodaSum = new int[SODAS];
int[] personSum = new int[PEOPLE];
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 114
for (int soda=0; soda < SODAS; soda++)
for (int person=0; person < PEOPLE; person++)
{
sodaSum[soda] += scores[soda][person];
personSum[person] += scores[soda][person];
}
DecimalFormat fmt = new DecimalFormat("0.#");
System.out.println("Averages:\n");
for (int soda=0; soda < SODAS; soda++)
System.out.println("Soda #" + (soda+1) + ": " +
fmt.format((float)sodaSum[soda]/PEOPLE));
System.out.println ();
for (int person=0; person < PEOPLE; person++)
System.out.println("Person #" + (person+1) + ": " +
fmt.format((float)personSum[person]/SODAS));
}
}
Code\chap7\SodaSurvey.java
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 115
Multidimensional Arrays
• Any array with more than one dimension is a
multidimensional array
• Each dimension subdivides the previous one into
the specified number of elements
• Each dimension has its own length constant
• Because each dimension is an array of array
references, the arrays within one dimension can
be of different lengths
– these are sometimes called ragged arrays
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 116
Multidimensional Arrays
• One way to visualize a four-dimensional array:
• Two-dimensional arrays are common, but
beyond that usually an array has other objects
involved
Java Foundations, 3rd Edition, Lewis/DePasquale/Chase
7 - 117