forked from ChrisMayfield/ThinkJava2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConway2.java
More file actions
61 lines (55 loc) · 1.84 KB
/
Copy pathConway2.java
File metadata and controls
61 lines (55 loc) · 1.84 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
// partial solution to File I/O exercises
// implemented as a method instead of a constructor
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Replaces grid based on a plain text file.
* http://www.conwaylife.com/wiki/Plaintext
*
* @param path the path to the file
* @param margin how many cells to add
*/
public void readFile(String path, int margin) {
// open the file at the given path
Scanner scan = null;
try {
File file = new File(path);
scan = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
// read file contents into memory
ArrayList<String> data = new ArrayList<String>();
while (scan.hasNextLine()) {
String line = scan.nextLine();
// only add non-comment lines
if (!line.startsWith("!")) {
data.add(line);
}
}
// determine number of rows and columns in the pattern
int rows = data.size();
int cols = 0;
for (String line : data) {
if (cols < line.length()) {
cols = line.length();
}
}
if (rows == 0 || cols == 0) {
throw new IllegalArgumentException("no cells found");
}
// create the resulting grid with margin of extra cells
grid = new GridCanvas(rows + 2 * margin, cols + 2 * margin, 20);
for (int r = 0; r < rows; r++) {
String line = data.get(r);
for (int c = 0; c < line.length(); c++) {
char x = line.charAt(c);
if (x == 'O') {
grid.turnOn(r + margin, c + margin);
}
}
}
}