Skip to content

Commit 3e64ced

Browse files
committed
added listing tags
1 parent 6f9e628 commit 3e64ced

1 file changed

Lines changed: 9 additions & 3 deletions

File tree

source/ch8_filehandling.ptx

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ public class CreateFile {
165165
<p>
166166
Consider the following Python code example that reads each line of the file and prints it to the console.
167167
</p>
168+
<data xml:id="myfile-read">
169+
<title>Data file for reading example</title>
168170
<datafile label="myfile-read" filename="myfile.txt" xml:id= "myfile-read" editable="no">
169171
<pre>
170172
1
@@ -177,8 +179,9 @@ public class CreateFile {
177179
8
178180
</pre>
179181
</datafile>
180-
181-
<program xml:id="file-read-python" interactive="activecode" language="python" add-files="myfile-read">
182+
</data>
183+
<listing xml:id="file-read-python">
184+
<program interactive="activecode" language="python" add-files="myfile-read">
182185
<code>
183186
filename = "myfile.txt"
184187
try:
@@ -192,12 +195,14 @@ public class CreateFile {
192195
print("file could not be opened")
193196
</code>
194197
</program>
198+
</listing>
195199

196200
<p>
197201
The following Java code functions very similarly to the previous Python. The main difference here is that unlike Python, in Java we use the <c>Scanner</c> object to iterate through and read lines in the file. You will notice that the structure of the Java code is still similar to the Python; Both use a try and catch statement to read the file and catch any errors.
198202
</p>
199203

200-
<program xml:id="file-read-java" interactive="activecode" language="java" add-files= "myfile-read">
204+
<listing xml:id="file-read-java">
205+
<program interactive="activecode" language="java" add-files= "myfile-read">
201206
<code>
202207
import java.io.File;
203208
import java.io.FileNotFoundException;
@@ -218,6 +223,7 @@ public class CreateFile {
218223
}
219224
</code>
220225
</program>
226+
</listing>
221227
<p>
222228
You may have noticed that there are some new methods you haven't seen yet. The <c>hasNextLine()</c> method checks if there is a next line in the file, and returns <c>false</c> if there isn't. This method allows us to iterate over every line till there is no next line. The <c>nextLine()</c> method of the Scanner object returns the next line in the file as a string.
223229
</p>

0 commit comments

Comments
 (0)