-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathArrayBasics.java
executable file
·89 lines (76 loc) · 2.94 KB
/
ArrayBasics.java
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
86
87
88
89
import java.util.Arrays;
public class ArrayBasics {
public static void main(String[] args) {
double[] scores = new double[5];
System.out.println("After double[] scores = new double[5]:");
for (int i = 0; i < 5; ++i) {
System.out.printf("scores[%d] = %.2f%n", i, scores[i]);
}
scores[0] = 89;
scores[1] = 100;
scores[2] = 95.6;
scores[3] = 84.5;
scores[4] = 91;
scores[scores.length - 1] = 99.2;
System.out.println("After element-by-element initialization:");
// Note: much better way to bound loop: using scores.length
for (int i = 0; i < scores.length; ++i) {
System.out.printf("scores[%d] = %.2f%n", i, scores[i]);
}
// Using traditional for loop with index, you can update array elements
for (int i = 0; i < scores.length; ++i) {
scores[i] = scores[i] - 10;
}
System.out.println("Each element decreased by 10:");
for (int i = 0; i < scores.length; ++i) {
System.out.printf("scores[%d] = %.2f%n", i, scores[i]);
}
// For-each loop parameter is a temporary variable/read-only iterator
for (double score: scores) {
score = score - 10;
System.out.println("score" + score);
}
System.out.println("For-each doesn't allow updates to array:");
for (int i = 0; i < scores.length; ++i) {
System.out.printf("scores[%d] = %.2f%n", i, scores[i]);
}
// System.out.println("Trying scores[scores.length] = 100 causes:");
// scores[scores.length] = 100;
double[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("Matrix:");
System.out.println(Arrays.toString(matrix));
double[][] doubledMatrix = scalarMult(2, matrix);
System.out.println("Doubled Matrix:");
System.out.println(arrayToString(doubledMatrix));
}
public static double[][] scalarMult(double x, double[][] a) {
double[][] result = new double[a.length][a[0].length];
// What if we initialized result with the parameter a?
// double[][] result = a;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
result[i][j] = x * a[i][j];
}
}
return result;
}
public static String arrayToString(double[] a) {
StringBuilder sb = new StringBuilder();
for (double e: a) {
sb.append(e + " ");
}
return sb.toString();
}
public static String arrayToString(double[][] a) {
StringBuilder sb = new StringBuilder();
for (double[] row: a) {
sb.append(Arrays.toString(row));
// Another way:
// for (double e: row) {
// sb.append(e + " ");
// }
sb.append(System.lineSeparator());
}
return sb.toString();
}
}