forked from e2xperimental/Programming-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayExercise.java
More file actions
85 lines (66 loc) · 1.44 KB
/
Copy pathArrayExercise.java
File metadata and controls
85 lines (66 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
#07
11/22/2010
Rectangle class, phase 5
*/
public class ArrayExercise
{
/**
Constructor
@param len The length of the rectangle.
@param w The width of the rectangle.
*/
public static void main(String[] args)
{
final int MAX_ROWS = 3;
final int MAX_COLS = 4;
// Create an array init to 0
int[][] numbers = new int[MAX_ROWS][MAX_COLS];
// print out
printArray(numbers, MAX_ROWS, MAX_COLS);
System.out.println();
// insert 1-12
insertSequential(numbers, MAX_ROWS, MAX_COLS);
// print out
printArray(numbers, MAX_ROWS, MAX_COLS);
System.out.println();
// add it up
int summer = sum(numbers, MAX_ROWS, MAX_COLS);
// print total
System.out.println("Sum = " + summer);
}
private static void insertSequential(int[][] array, int Rows, int Cols)
{
int s = 1;
for (int row = 0; row < Rows; row++)
{
for (int col = 0; col < Cols; col++)
{
array[row][col] = s++;
}
}
}
private static int sum(int[][] array, int Rows, int Cols)
{
int s = 1;
for (int row = 0; row < Rows; row++)
{
for (int col = 0; col < Cols; col++)
{
s += array[row][col];
}
}
return s;
}
private static void printArray(int[][] array, int Rows, int Cols)
{
for (int row = 0; row < Rows; row++)
{
for (int col = 0; col < Cols; col++)
{
System.out.print(array[row][col] + "\t");
}
System.out.println();
}
}
}