Presentation is loading. Please wait.

Presentation is loading. Please wait.

Example: Finding the Mode

Similar presentations


Presentation on theme: "Example: Finding the Mode"— Presentation transcript:

1 Example: Finding the Mode
Given: A sequence of integers Goal: Determine the mod of the set The number which appears the most number of times

2 Example: Finding the Mode
Algorithm: Generate an array of 100 random numbers from 1 to 10 Use a length 10 array to count how many times each number appears in the array Report the one that appears the most, or multiple if there are ties

3 exceptions Motivation: it would be nice to “monitor” the flow of a program for certain bugs Invalid input Invalid array access Type mismatches Recall the example of trying to validate a user input, ensuring that they enter a positive integer Requires slightly confusing loop logic to manage each case Use Scanner.hasNextInt(), etc.

4 Exceptions Example: int x;
x = “1”; // “throws” a NumberFormatException int[] myArray = new int[5]; myArray[5] = 1; // “throws” a ArrayIndexOutOfBoundsException

5 exceptions If a program raises an exception, it crashes!
… unless we “catch” it! Syntax: the “try…catch” block

6 Try ... Catch Syntax: try { <statements-1>
} catch ( <exception-class-name> <variable-name> ) { <statements-2> } We can also chain more “catch” blocks for different types of exceptions

7 Try…catch Behavior: if the code inside the “try” block raises an exception that matches an exception in the “catch” block, it will immediately stop executing the “try” and start executing the “catch” block int[] myArray = new int[100]; try { myArray[100] = 1; } catch ( ArrayIndexOutOfBoundsException e ){ System.out.println(“You accessed an invalid element!”); }

8 Example: Input Validation
Ask the user for an array of integers, validate each Print the average of the array


Download ppt "Example: Finding the Mode"

Similar presentations


Ads by Google