- •CONTENTS
- •1.1 Introduction
- •1.2 What Is a Computer?
- •1.3 Programs
- •1.4 Operating Systems
- •1.5 Java, World Wide Web, and Beyond
- •1.6 The Java Language Specification, API, JDK, and IDE
- •1.7 A Simple Java Program
- •1.8 Creating, Compiling, and Executing a Java Program
- •1.9 (GUI) Displaying Text in a Message Dialog Box
- •2.1 Introduction
- •2.2 Writing Simple Programs
- •2.3 Reading Input from the Console
- •2.4 Identifiers
- •2.5 Variables
- •2.7 Named Constants
- •2.8 Numeric Data Types and Operations
- •2.9 Problem: Displaying the Current Time
- •2.10 Shorthand Operators
- •2.11 Numeric Type Conversions
- •2.12 Problem: Computing Loan Payments
- •2.13 Character Data Type and Operations
- •2.14 Problem: Counting Monetary Units
- •2.15 The String Type
- •2.16 Programming Style and Documentation
- •2.17 Programming Errors
- •2.18 (GUI) Getting Input from Input Dialogs
- •3.1 Introduction
- •3.2 boolean Data Type
- •3.3 Problem: A Simple Math Learning Tool
- •3.4 if Statements
- •3.5 Problem: Guessing Birthdays
- •3.6 Two-Way if Statements
- •3.7 Nested if Statements
- •3.8 Common Errors in Selection Statements
- •3.9 Problem: An Improved Math Learning Tool
- •3.10 Problem: Computing Body Mass Index
- •3.11 Problem: Computing Taxes
- •3.12 Logical Operators
- •3.13 Problem: Determining Leap Year
- •3.14 Problem: Lottery
- •3.15 switch Statements
- •3.16 Conditional Expressions
- •3.17 Formatting Console Output
- •3.18 Operator Precedence and Associativity
- •3.19 (GUI) Confirmation Dialogs
- •4.1 Introduction
- •4.2 The while Loop
- •4.3 The do-while Loop
- •4.4 The for Loop
- •4.5 Which Loop to Use?
- •4.6 Nested Loops
- •4.7 Minimizing Numeric Errors
- •4.8 Case Studies
- •4.9 Keywords break and continue
- •4.10 (GUI) Controlling a Loop with a Confirmation Dialog
- •5.1 Introduction
- •5.2 Defining a Method
- •5.3 Calling a Method
- •5.4 void Method Example
- •5.5 Passing Parameters by Values
- •5.6 Modularizing Code
- •5.7 Problem: Converting Decimals to Hexadecimals
- •5.8 Overloading Methods
- •5.9 The Scope of Variables
- •5.10 The Math Class
- •5.11 Case Study: Generating Random Characters
- •5.12 Method Abstraction and Stepwise Refinement
- •6.1 Introduction
- •6.2 Array Basics
- •6.3 Problem: Lotto Numbers
- •6.4 Problem: Deck of Cards
- •6.5 Copying Arrays
- •6.6 Passing Arrays to Methods
- •6.7 Returning an Array from a Method
- •6.8 Variable-Length Argument Lists
- •6.9 Searching Arrays
- •6.10 Sorting Arrays
- •6.11 The Arrays Class
- •7.1 Introduction
- •7.2 Two-Dimensional Array Basics
- •7.3 Processing Two-Dimensional Arrays
- •7.4 Passing Two-Dimensional Arrays to Methods
- •7.5 Problem: Grading a Multiple-Choice Test
- •7.6 Problem: Finding a Closest Pair
- •7.7 Problem: Sudoku
- •7.8 Multidimensional Arrays
- •8.1 Introduction
- •8.2 Defining Classes for Objects
- •8.3 Example: Defining Classes and Creating Objects
- •8.4 Constructing Objects Using Constructors
- •8.5 Accessing Objects via Reference Variables
- •8.6 Using Classes from the Java Library
- •8.7 Static Variables, Constants, and Methods
- •8.8 Visibility Modifiers
- •8.9 Data Field Encapsulation
- •8.10 Passing Objects to Methods
- •8.11 Array of Objects
- •9.1 Introduction
- •9.2 The String Class
- •9.3 The Character Class
- •9.4 The StringBuilder/StringBuffer Class
- •9.5 Command-Line Arguments
- •9.6 The File Class
- •9.7 File Input and Output
- •9.8 (GUI) File Dialogs
- •10.1 Introduction
- •10.2 Immutable Objects and Classes
- •10.3 The Scope of Variables
- •10.4 The this Reference
- •10.5 Class Abstraction and Encapsulation
- •10.6 Object-Oriented Thinking
- •10.7 Object Composition
- •10.8 Designing the Course Class
- •10.9 Designing a Class for Stacks
- •10.10 Designing the GuessDate Class
- •10.11 Class Design Guidelines
- •11.1 Introduction
- •11.2 Superclasses and Subclasses
- •11.3 Using the super Keyword
- •11.4 Overriding Methods
- •11.5 Overriding vs. Overloading
- •11.6 The Object Class and Its toString() Method
- •11.7 Polymorphism
- •11.8 Dynamic Binding
- •11.9 Casting Objects and the instanceof Operator
- •11.11 The ArrayList Class
- •11.12 A Custom Stack Class
- •11.13 The protected Data and Methods
- •11.14 Preventing Extending and Overriding
- •12.1 Introduction
- •12.2 Swing vs. AWT
- •12.3 The Java GUI API
- •12.4 Frames
- •12.5 Layout Managers
- •12.6 Using Panels as Subcontainers
- •12.7 The Color Class
- •12.8 The Font Class
- •12.9 Common Features of Swing GUI Components
- •12.10 Image Icons
- •13.1 Introduction
- •13.2 Exception-Handling Overview
- •13.3 Exception-Handling Advantages
- •13.4 Exception Types
- •13.5 More on Exception Handling
- •13.6 The finally Clause
- •13.7 When to Use Exceptions
- •13.8 Rethrowing Exceptions
- •13.9 Chained Exceptions
- •13.10 Creating Custom Exception Classes
- •14.1 Introduction
- •14.2 Abstract Classes
- •14.3 Example: Calendar and GregorianCalendar
- •14.4 Interfaces
- •14.5 Example: The Comparable Interface
- •14.6 Example: The ActionListener Interface
- •14.7 Example: The Cloneable Interface
- •14.8 Interfaces vs. Abstract Classes
- •14.9 Processing Primitive Data Type Values as Objects
- •14.10 Sorting an Array of Objects
- •14.11 Automatic Conversion between Primitive Types and Wrapper Class Types
- •14.12 The BigInteger and BigDecimal Classes
- •14.13 Case Study: The Rational Class
- •15.1 Introduction
- •15.2 Graphical Coordinate Systems
- •15.3 The Graphics Class
- •15.4 Drawing Strings, Lines, Rectangles, and Ovals
- •15.5 Case Study: The FigurePanel Class
- •15.6 Drawing Arcs
- •15.7 Drawing Polygons and Polylines
- •15.8 Centering a String Using the FontMetrics Class
- •15.9 Case Study: The MessagePanel Class
- •15.10 Case Study: The StillClock Class
- •15.11 Displaying Images
- •15.12 Case Study: The ImageViewer Class
- •16.1 Introduction
- •16.2 Event and Event Source
- •16.3 Listeners, Registrations, and Handling Events
- •16.4 Inner Classes
- •16.5 Anonymous Class Listeners
- •16.6 Alternative Ways of Defining Listener Classes
- •16.7 Problem: Loan Calculator
- •16.8 Window Events
- •16.9 Listener Interface Adapters
- •16.10 Mouse Events
- •16.11 Key Events
- •16.12 Animation Using the Timer Class
- •17.1 Introduction
- •17.2 Buttons
- •17.3 Check Boxes
- •17.4 Radio Buttons
- •17.5 Labels
- •17.6 Text Fields
- •17.7 Text Areas
- •17.8 Combo Boxes
- •17.9 Lists
- •17.10 Scroll Bars
- •17.11 Sliders
- •17.12 Creating Multiple Windows
- •18.1 Introduction
- •18.2 Developing Applets
- •18.3 The HTML File and the <applet> Tag
- •18.4 Applet Security Restrictions
- •18.5 Enabling Applets to Run as Applications
- •18.6 Applet Life-Cycle Methods
- •18.7 Passing Strings to Applets
- •18.8 Case Study: Bouncing Ball
- •18.9 Case Study: TicTacToe
- •18.10 Locating Resources Using the URL Class
- •18.11 Playing Audio in Any Java Program
- •18.12 Case Study: Multimedia Animations
- •19.1 Introduction
- •19.2 How is I/O Handled in Java?
- •19.3 Text I/O vs. Binary I/O
- •19.4 Binary I/O Classes
- •19.5 Problem: Copying Files
- •19.6 Object I/O
- •19.7 Random-Access Files
- •20.1 Introduction
- •20.2 Problem: Computing Factorials
- •20.3 Problem: Computing Fibonacci Numbers
- •20.4 Problem Solving Using Recursion
- •20.5 Recursive Helper Methods
- •20.6 Problem: Finding the Directory Size
- •20.7 Problem: Towers of Hanoi
- •20.8 Problem: Fractals
- •20.9 Problem: Eight Queens
- •20.10 Recursion vs. Iteration
- •20.11 Tail Recursion
- •APPENDIXES
- •INDEX
244 Chapter 7 |
Multidimensional Arrays |
|
The program prompts the user to enter the number of points (lines 6–7). The points are read |
|
from the console and stored in a two-dimensional array named points (lines 12–15). The |
|
program uses variable shortestDistance (line 19) to store the distance between two near- |
|
est points, and the indices of these two points in the points array are stored in p1 and p2 |
|
(line 18). |
|
For each point at index i, the program computes the distance between points[i] and |
|
points[j] for all j > i (lines 23–34). Whenever a shorter distance is found, the variable |
|
shortestDistance and p1 and p2 are updated (lines 28–32). |
|
The distance between two points (x1, y1) and (x2, y2) can be computed using the |
|
formula 21x2 - x122 + 1y2 - y122 (lines 43–46). |
|
The program assumes that the plane has at least two points. You can easily modify the pro- |
|
gram to handle the case if the plane has zero or one point. |
multiple closest pairs |
Note that there might be more than one closest pair of points with the same minimum dis- |
|
tance. The program finds one such pair. You may modify the program to find all closest pairs |
|
in Programming Exercise 7.8. |
|
Tip |
input file |
It is cumbersome to enter all points from the keyboard. You may store the input in a file, say |
|
FindNearestPoints.txt, and compile and run the program using the following command: |
|
java FindNearestPoints < FindNearestPoints.txt |
Video Note
Sudoku
fixed cells free cells
7.7 Problem: Sudoku
This book teaches how to program using a wide variety of problems with various levels of difficulty. We use simple, short, and stimulating examples to introduce programming and problem-solving techniques and use interesting and challenging examples to motivate students. This section presents an interesting problem of a sort that appears in the newspaper every day. It is a number-placement puzzle, commonly known as Sudoku. This is a very challenging problem. To make it accessible to the novice, this section presents a solution to a simplified version of the Sudoku problem, which is to verify whether a solution is correct. The complete solution for solving the Sudoku problem is presented in Supplement VII.A.
Sudoku is a 9 * 9 grid divided into smaller 3 * 3 boxes (also called regions or blocks), as shown in Figure 7.4(a). Some cells, called fixed cells, are populated with numbers from 1 to 9. The objective is to fill the empty cells, also called free cells, with numbers 1 to 9 so that every row, every column, and every 3 * 3 box contains the numbers 1 to 9, as shown in Figure 7.4(b).
5 |
3 |
|
7 |
|
|
5 |
3 |
4 |
6 |
7 |
8 |
9 |
1 |
2 |
6 |
|
1 |
9 |
5 |
|
6 |
7 |
2 |
1 |
9 |
5 |
3 |
4 |
8 |
|
9 |
8 |
|
6 |
|
1 |
9 |
8 |
3 |
4 |
2 |
5 |
6 |
7 |
8 |
|
|
6 |
|
3 |
8 |
5 |
9 |
7 |
6 |
1 |
4 |
2 |
3 |
4 |
|
8 |
|
3 |
1 |
Solution |
2 |
6 |
8 |
5 |
3 |
7 |
9 |
1 |
|
|
4 |
||||||||||||
7 |
|
|
2 |
|
6 |
7 |
1 |
3 |
9 |
2 |
4 |
8 |
5 |
6 |
|
6 |
|
|
|
|
9 |
6 |
1 |
5 |
3 |
7 |
2 |
8 |
4 |
|
|
4 |
1 |
9 |
5 |
2 |
8 |
7 |
4 |
1 |
9 |
6 |
3 |
5 |
|
|
|
8 |
7 |
9 |
3 |
4 |
5 |
2 |
8 |
6 |
1 |
7 |
9 |
|
|
(a) Puzzle |
|
|
|
|
(b) Solution |
|
|
|
FIGURE 7.4 The Sudoku puzzle in (a) is solved in (b).
|
|
|
|
|
|
|
|
|
|
7.7 |
Problem: Sudoku 245 |
||
For convenience, we use value 0 to indicate a free cell, as shown in Figure 7.5(a). The grid |
representing a grid |
||||||||||||
can be naturally represented using a two-dimensional array, as shown in Figure 7.5(a). |
|
||||||||||||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
3 |
0 |
0 |
7 |
0 |
0 |
0 |
0 |
|
int[][] grid = |
|
|
|
6 |
0 |
0 |
1 |
9 |
5 |
0 |
0 |
0 |
|
{{5, 3, 0, 0, 7, 0, 0, 0, 0}, |
|
|
|
0 |
9 |
8 |
0 |
0 |
0 |
0 |
6 |
0 |
|
{6, 0, 0, 1, 9, 5, 0, 0, 0}, |
|
|
|
|
{0, 9, 8, 0, 0, 0, 0, 6, 0}, |
|
|
|||||||||
|
8 |
0 |
0 |
0 |
6 |
0 |
0 |
0 |
3 |
|
|
|
|
|
|
{8, 0, 0, 0, 6, 0, 0, 0, 3}, |
|
|
|||||||||
|
4 |
0 |
0 |
8 |
0 |
3 |
0 |
0 |
1 |
|
{4, 0, 0, 8, 0, 3, 0, 0, 1}, |
|
|
|
7 |
0 |
0 |
0 |
2 |
0 |
0 |
0 |
6 |
|
{7, 0, 0, 0, 2, 0, 0, 0, 6}, |
|
|
|
|
{0, 6, 0, 0, 0, 0, 2, 8, 0}, |
|
|
|||||||||
|
0 |
6 |
0 |
0 |
0 |
0 |
0 |
0 |
0 |
|
|
|
|
|
|
{0, 0, 0, 4, 1, 9, 0, 0, 5}, |
|
|
|||||||||
|
0 |
0 |
0 |
4 |
1 |
9 |
0 |
0 |
5 |
|
{0, 0, 0, 0, 8, 0, 0, 7, 9} |
|
|
|
0 |
0 |
0 |
0 |
8 |
0 |
0 |
7 |
9 |
|
}; |
|
|
|
|
|
|
|
(a) |
|
|
|
|
|
(b) |
|
|
FIGURE 7.5 A grid can be represented using a two-dimensional array.
To find a solution for the puzzle we must replace each 0 in the grid with an appropriate number from 1 to 9. For the solution in Figure 7.4(b), the grid should be as shown in Figure 7.6.
A solution grid is
{{5, 3, 4, 6, 7, 8, 9, 1, 2}, {6, 7, 2, 1, 9, 5, 3, 4, 8}, {1, 9, 8, 3, 4, 2, 5, 6, 7}, {8, 5, 9, 7, 6, 1, 4, 2, 3}, {4, 2, 6, 8, 5, 3, 7, 9, 1}, {7, 1, 3, 9, 2, 4, 8, 5, 6}, {9, 6, 1, 5, 3, 7, 2, 8, 4}, {2, 8, 7, 4, 1, 9, 6, 3, 5}, {3, 4, 5, 2, 8, 6, 1, 7, 9} };
FIGURE 7.6 A solution is stored in grid.
A simplified version of the Sudoku problem is to check the validity of a solution. The program in Listing 7.4 prompts the user to enter a solution and reports whether it is valid.
LISTING 7.4 CheckSudokuSolution.java
1 import java.util.Scanner;
2
3 public class CheckSudokuSolution {
4 public static void main(String[] args) {
5// Read a Sudoku solution
6 int[][] grid = readASolution();
7
8 System.out.println(isValid(grid) ? "Valid solution" :
9 "Invalid solution");
10 }
11
12/** Read a Sudoku solution from the console */
13public static int[][] readASolution() {
14// Create a Scanner
15Scanner input = new Scanner(System.in);
read input
solution valid?
read solution
246 Chapter 7 |
Multidimensional Arrays |
|||||||||||||
|
16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
System.out.println("Enter a Sudoku puzzle solution:"); |
|||||||||||
|
18 |
|
int[][] grid = new int[9][9]; |
|||||||||||
|
19 |
|
for (int i = 0; i < 9; i++) |
|||||||||||
|
20 |
|
for (int j = 0; j < 9; j++) |
|||||||||||
|
21 |
|
grid[i][j] = input.nextInt(); |
|||||||||||
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
return grid; |
|||||||||||
|
24 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
/** Check whether a solution is valid */ |
||||||||||||
check solution |
27 |
public static boolean isValid(int[][] grid) { |
|
|||||||||||
|
28 |
|
// Check whether each row has numbers 1 to 9 |
|||||||||||
check rows |
29 |
|
for (int i = 0; i < 9; i++) |
|
|
|||||||||
|
30 |
|
if |
(!is1To9(grid[i]) |
) // If grid[i] does not contain 1 to 9 |
|||||||||
|
31 |
|
return false; |
|||||||||||
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
// Check whether each column has numbers 1 to 9 |
|||||||||||
check columns |
34 |
|
for (int j = 0; j < 9; j++) { |
|
|
|||||||||
|
35 |
|
// Obtain a column in the one-dimensional array |
|||||||||||
|
36 |
|
int[] column = new int[9]; |
|||||||||||
|
37 |
|
for (int i = 0; i < 9; i++) { |
|||||||||||
|
38 |
|
column[i] = grid[i][j]; |
|||||||||||
|
39 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
40 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
if |
(!is1To9(column) |
) // If column does not contain 1 to 9 |
|||||||||
|
42 |
|
return false; |
|||||||||||
|
43 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
// Check whether each 3-by-3 box has numbers 1 to 9 |
|||||||||||
check small boxes |
46 |
|
for (int i = 0; i < 3; i++) { |
|
|
|||||||||
|
47 |
|
for (int j = 0; j < 3; j++) { |
|||||||||||
|
48 |
|
// The starting element in a small 3-by-3 box |
|||||||||||
|
49 |
|
int k = 0; |
|||||||||||
|
50 |
|
int[] list = new int[9]; // Get all numbers in the box to list |
|||||||||||
|
51 |
|
for (int row = i * 3; row < i * 3 + 3; row ++) |
|||||||||||
|
52 |
|
|
for (int column = j * 3; column < j * 3 + 3; column++) |
||||||||||
|
53 |
|
|
|
list[k++] = grid[row][column]; |
|||||||||
|
54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
if |
(!is1To9(list) |
) // If list does not contain 1 to 9 |
|||||||||
|
56 |
|
|
|
return false; |
|||||||||
|
57 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
all valid |
60 |
|
return true; // The fixed cells are valid |
|||||||||||
|
61 |
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
/** Check whether the one-dimensional array contains 1 to 9 */ |
||||||||||||
contains 1 to 9 ? |
64 |
public static boolean is1To9(int[] list) { |
||||||||||||
|
65 |
|
// Make a copy of the array |
|||||||||||
|
66 |
|
int[] temp = new int[list.length]; |
|||||||||||
copy of array |
67 |
|
System.arraycopy(list, 0, temp, 0, list.length); |
|
||||||||||
|
68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
// Sort the array |
|||||||||||
sort array |
70 |
|
java.util.Arrays.sort(temp); |
|
|
|
|
|||||||
|
71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
// Check whether the list contains 1, 2, 3, ..., 9 |
|||||||||||
check 1 to 9 |
73 |
|
for (int i = 0; i < 9; i++) |
7.7 Problem: Sudoku 247
74if (temp[i] != i + 1)
75return false;
76
77return true; // The list contains exactly 1 to 9
78}
79}
Enter a Sudoku puzzle solution: 9 6 3 1 7 4 2 5 8 1 7 8 3 2 5 6 4 9 2 5 4 6 8 9 7 3 1 8 2 1 4 3 7 5 9 6 4 9 6 8 5 2 3 1 7 7 3 5 9 6 1 8 2 4 5 8 9 7 1 3 4 6 2 3 1 7 2 4 6 9 8 5 6 4 2 5 9 8 1 7 3
Valid solution
The program invokes the readASolution() method (line 6) to read a Sudoku solution and return a two-dimensional array representing a Sudoku grid.
The isValid(grid) method (lines 27–61) checks whether every row contains numbers 1 to 9 (lines 29–31). grid is a two-dimensional array. grid[i] is a one-dimensional array for the ith row. Invoking is1To9(grid[i]) returns true if the row grid[i] contains exactly numbers from 1 to 9 (line 30).
To check whether each column in grid has numbers 1 to 9, get a column into a onedimensional array (lines 36–39) and invoke the is1To9 method to check whether it has 1 to 9 (line 41).
To check whether each small 3 * 3 box in grid has numbers 1 to 9, get a box into a onedimensional array (lines 49–53) and invoke the is1To9 method to check whether it has 1 to 9 (line 55).
How do you locate all the cells in the same box? First, locate the starting cells of the 3 * 3 boxes. They are at (3i, 3j) for i = 0, 1, 2 and j = 0, 1, 2, as illustrated in Figure 7.7.
isValid method check rows
check columns
check small boxes
grid[0][0] |
grid[0][6] |
grid[6][3]
The location of the starting cell for each grid is at (3*i, 3*j) for i = 0, 1, 2 and j = 0, 1, 2. For example, grid[6][3]).
FIGURE 7.7 The location of the first cell in a 3 * 3 box determines the locations of other cells in the box.