Skip to content

Commit ef20757

Browse files
authored
Merge branch 'RunestoneInteractive:master' into Issue-#127-Fix
2 parents c085b2d + 3187210 commit ef20757

2 files changed

Lines changed: 161 additions & 15 deletions

File tree

source/ch4_conditionals.ptx

Lines changed: 157 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -163,17 +163,18 @@ public class ElseIf {
163163

164164
<p>
165165
Java also supports a <c>switch</c> statement that acts something like the <c>elif</c> statement of Python under certain conditions. To write the grade program using a <c>switch</c> statement we would use the following:
166-
</p>
166+
</p>
167167

168168
<note>
169169
<p>
170-
Depending on your knowledge and experience with Python you may already be familiar and questioning why we are not using the <c>match</c> statement in our Python examples. The answer is that this book currently runs its active code examples on Python 3.7, which does not support the <c>match</c> statement. The <c>match</c> statement was introduced in Python 3.10. Below is an example of the <c>match</c> statement similar to our grade method.
170+
Depending on your knowledge and experience with Python you may already be familiar and questioning why we are not using the <c>match</c> statement in our Python examples. The answer is that this book currently runs its active code examples using Python 3.7, which does not support the <c>match</c> statement which was introduced in Python 3.10. Below is an example of the <c>match</c> statement similar to our grade method.
171171
</p>
172172
<program language="python">
173173
<title>Match Case Example</title>
174174
<code>
175-
grade = 100 // 10
176-
def grading(grade):
175+
grade = 85
176+
tempgrade = grade // 10
177+
def grading(tempgrade):
177178
match grade:
178179
case 10 | 9:
179180
return 'A'
@@ -185,7 +186,7 @@ Java also supports a <c>switch</c> statement that acts something like the <c>eli
185186
return 'D'
186187
case _:
187188
return 'F'
188-
print(grading(grade))
189+
print(grading(tempgrade))
189190
</code>
190191
</program>
191192
</note>
@@ -234,6 +235,157 @@ The <c>switch</c> statement is not used very often, and we recommend you do not
234235
</p>
235236
</section>
236237

238+
<section xml:id="exception-handling">
239+
<title>Exception Handling</title>
240+
241+
<p>
242+
In Python, if you want a program to continue running when an error has occurred, you can use <c>try-except</c> blocks to handle exceptions. If you wanted to write a program that asks the user to enter a whole number and then squares that number, you could use the following code to do so:
243+
</p>
244+
245+
<program interactive="activecode" language="python" xml:id="square-input-python">
246+
<code>
247+
number = int(input("Please enter a whole number: "))
248+
squared = number ** 2
249+
print("Your number squared is " + str(squared))
250+
</code>
251+
</program>
252+
253+
<p>
254+
The Java code that would perform the same task is a little more complex and utilizes the <c>Scanner</c> class for input.
255+
</p>
256+
257+
<program interactive="activecode" language="java" xml:id="square-input-java">
258+
<code>
259+
import java.util.Scanner;
260+
261+
public class SquareNumber {
262+
public static void main(String[] args) {
263+
Scanner user_input = new Scanner(System.in);
264+
265+
System.out.print("Please enter a whole number: ");
266+
int number = user_input.nextInt();
267+
int squared = number * number;
268+
269+
System.out.println("Your number squared is " + squared);
270+
}
271+
}
272+
</code>
273+
</program>
274+
275+
<p>
276+
This code works well, but will end with an exception if the user types anything other than a whole number (such as 12.5 or two). If we wanted to ensure the code will continue to run until the user enters the correct format, we could add <c>try-except</c> (Python) or <c>try-catch</c> (Java) blocks within a <c>while</c> loop that iterates until the user enter the correct code. Adding <c>try-except</c> blocks and a <c>while</c> loop to the Python code will look something like this:
277+
</p>
278+
279+
<program interactive="activecode" language="python" xml:id="square-input-exception-python">
280+
<code>
281+
while True:
282+
try:
283+
number = int(input("Please enter a whole number: "))
284+
squared = number ** 2
285+
print("Your number squared is " + str(squared))
286+
break
287+
except ValueError:
288+
print("That was not a valid number. Please try again: ")
289+
</code>
290+
</program>
291+
292+
<p>
293+
Now that we have Python code that will continuously prompt the user until they enter a whole number, let's look at Java code that accomplishes the same task. Like most other equivalent Java code blocks, this code has a lot of extra bits that are necessary to get working code.
294+
</p>
295+
296+
<program interactive="activecode" language="java" xml:id="square-input-exception-java">
297+
<code>
298+
import java.util.Scanner;
299+
import java.util.InputMismatchException;
300+
301+
public class SquareNumberWithValidation {
302+
public static void main(String[] args) {
303+
Scanner scanner = new Scanner(System.in);
304+
305+
while (true) {
306+
try {
307+
System.out.print("Please enter a whole number: ");
308+
int number = scanner.nextInt();
309+
int squared = number * number;
310+
System.out.println("Your number squared is " + squared);
311+
break;
312+
} catch (InputMismatchException e) {
313+
System.out.println("That was not a valid number. Please try again: ");
314+
scanner.nextLine(); // Clear the invalid input from the scanner
315+
}
316+
}
317+
}
318+
}
319+
</code>
320+
</program>
321+
322+
<p>
323+
Firstly, let's talk about the extra import alongside the <c>Scanner</c> import. In Java, we need to import <c>InputMismatchException</c> because it's not automatically available like basic exceptions. This is different from Python where most exceptions are readily accessible. If you ran the previous Java codeblock without <c>try-catch</c> blocks and entered an erroneous input, you would have got an <c>InputMismatchException</c> exception despite not having imported this class. That being said, removing the explicit import of this library for the <c>try-catch</c> code block above will lead to compilation errors.
324+
</p>
325+
326+
<p>
327+
<idx>checked exception</idx>
328+
<idx>unchecked exception</idx>
329+
Exceptions in Java fall under two categories: checked and unchecked. <term>Checked exceptions</term> must be explicitly imported and declared along with <c>try-catch</c> blocks for a program to compile. <term>Unchecked exceptions</term> do not need to be imported unless <c>try-catch</c> blocks are implemented for them (except for <c>java.lang</c> exceptions). <c>InputMismatchException</c> is an unchecked exception that is not part of the <c>java.lang</c> library, so it is only included if <c>try-catch</c> blocks declare it. Here are some common exceptions used with <c>try-catch</c> blocks:
330+
</p>
331+
332+
<table>
333+
<title>Exceptions</title>
334+
<tabular>
335+
<row>
336+
<cell><term>Exception</term></cell>
337+
<cell><term>Package</term></cell>
338+
<cell><term>Description</term></cell>
339+
</row>
340+
<row>
341+
<cell><c>IOException</c></cell>
342+
<cell><c>java.io</c></cell>
343+
<cell>Thrown when an I/O operation fails (e.g., reading or writing a file).</cell>
344+
</row>
345+
<row>
346+
<cell><c>FileNotFoundException</c></cell>
347+
<cell><c>java.io</c></cell>
348+
<cell>Thrown when an attempt to open a file denoted by a pathname has failed.</cell>
349+
</row>
350+
<row>
351+
<cell><c>ParseException</c></cell>
352+
<cell><c>java.text</c></cell>
353+
<cell>Thrown when parsing a string into a date, number, etc. fails (e.g., wrong format).</cell>
354+
</row>
355+
<row>
356+
<cell><c>NoSuchMethodException</c></cell>
357+
<cell><c>java.lang</c></cell>
358+
<cell>Thrown when a particular method cannot be found via reflection.</cell>
359+
</row>
360+
<row>
361+
<cell><c>InputMismatchException</c></cell>
362+
<cell><c>java.util</c></cell>
363+
<cell>Thrown when <c>Scanner</c> input doesn’t match the expected data type.</cell>
364+
</row>
365+
<row>
366+
<cell><c>SQLException</c></cell>
367+
<cell><c>java.sql</c></cell>
368+
<cell>Thrown when a database access error occurs (e.g., invalid SQL query, bad connection).</cell>
369+
</row>
370+
<row>
371+
<cell><c>InstantiationException</c></cell>
372+
<cell><c>java.lang</c></cell>
373+
<cell>Thrown when trying to create an instance of an abstract class or interface.</cell>
374+
</row>
375+
<row>
376+
<cell><c>IllegalAccessException</c></cell>
377+
<cell><c>java.lang</c></cell>
378+
<cell>Thrown when a reflection operation tries to access a field or method it doesn't have permission for.</cell>
379+
</row>
380+
</tabular>
381+
</table>
382+
383+
<p>
384+
Note that as with other structures in Java, <c>try-catch</c> blocks blocks must be encased with braces <c>{}</c>. The most important part of this code is, after <c>catch</c>, there is a set of parenthesis with an exception type and a variable name <c>catch (InputMismatchException e)</c>. This is where we declare a <c>InputMismatchException</c> exception and name it with the variable name <c>e</c>. It is common practice, though not a requirement, to name exception variables <c>e</c> in this manner.
385+
</p>
386+
387+
</section>
388+
237389
<section xml:id="boolean-operators">
238390
<title>Boolean Operators</title>
239391

source/ch8_filehandling.ptx

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,10 @@
44
<chapter xml:id="filemmanipulation">
55
<title>File Handling</title>
66

7-
<introduction>
8-
<p>
9-
File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files.
10-
</p>
11-
</introduction>
12-
13-
147
<section xml:id="file-class-import">
158
<title>Class Imports</title>
169
<p>
17-
In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like <c>math</c> do need to be imported. Consider the following.
10+
File handling is an integral part of programming. Most programming languages have the ability to read from, write to, create, delete, move, and copy files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like <c>math</c> do need to be imported. Consider the following.
1811
</p>
1912
<program xml:id = "file-class-import-Python-example" interactive="activecode" language="python">
2013
<code>
@@ -42,12 +35,13 @@
4235
</p>
4336

4437
<p>
45-
Java includes a class called <c>File</c> in the <c>io</c> library. The class can be imported with the following line. Be sure to capitalize <c>File</c>.
38+
Much like the Math class, in order for your program to work with files you need to import classes from libraries. Java includes a class called <c>File</c> in the <c>io</c> library. This class allows you to create File objects, and use its public methods. the following code imports the <c>File</c> class and creates a <c>File</c> object called myFile. for now focus on how the class is imported and used in the program; We will cover the <c>IOException</c> class and <c>createNewFile</c> method later.
4639
</p>
4740
<program xml:id = "file-class-import-io-example" interactive="activecode" language="java">
4841
<code>
4942
import java.io.File;
50-
import java.io.IOException;public class Main {
43+
import java.io.IOException;
44+
public class Main {
5145
public static void main(String[] args) {
5246
try {
5347
File myFile = new File("newfile.txt");

0 commit comments

Comments
 (0)