Download presentation
Presentation is loading. Please wait.
Published byBetty Fox Modified over 9 years ago
1
week91 APCS-AB: Java Problem Solving November 1, 2005
2
week92 How you problem solve What do you do when faced with a new problem? For the logic puzzles yesterday, how did you figure out a solution? For the Scheme and Java projects in Q1, how did you come up with a good solution?
3
week93 Today We are going to look at a general method of problem solving You can compare this with what you already do This may or may not improve what you already instinctively do, and if nothing else, it might help you help a friend who’s struggling with a problem
4
week94 Problem Solving – 4 phases Understanding the problem Devising a plan Carrying out the plan Looking back (testing solution) From “How to Solve It” By G. Polya
5
week95 Understanding the problem Read it – do you understand what it is asking? Think about what it is asking you to do What are the inputs to the problem? What are the outputs of your solution? Are there any conditions? Draw a figure, show a sample of the problem.
6
week96 Devising a plan Have you seen a similar problem before? Or have you seen something like this problem in a different form? Can you restate the problem? Can you think of a more general problem? A more special problem? Can you solve part of the problem? Draw out what you think might work Think about and name the variables you might need Think about what kind of conditional structures might be suited to the problem Pseudocode your plan
7
week97 Carrying out the plan Program your plan, checking each step. Is that line of code correct? Is it doing what you want/expect it to?
8
week98 Looking back (testing solution) Examine your solution Make sure that you get the expected output Step through your program and trace its state at each step Follow through your code and make sure you didn’t stop earlier, and that your variables get the value that you expected For problems with loops, draw a grid and trace each step through the code
9
week99 Method Level Problem Solving Understanding the problem What exactly does this method need to do? What are the inputs to the problem? What are the outputs of your solution? Are there any conditions? What must be true before this method starts (pre- conditions) Could assert they are true before the method continues: What will be true when this method finished (post- conditions)
10
week910 Method Level Problem Solving Devising a plan Is there a related method we could modify? PSEUDOCODE Identify and name variables, Think about the conditional structures you need lay out the steps the method needs to do Carrying out the plan Turn the pseudocode into Java code Looking Back (testing solution) Step through your program. Do the pre-conditions hold? Do the post-conditions?
11
week911 APCS-AB: Java Problem Solving cont’d November 2, 2005
12
week912 Codebreaker Example Let’s look at how we solved the odd character substitution problem: For this method you are going to replace every other letter by its “pair” letter. A pair letter is the letter that is 13 letters away from the letter (like a- n, b-o, c-p, etc). a.For example, “string” becomes “fteiag” Let’s try to apply the strategy from today to this problem Then let’s look at one solution I received that didn’t quite work and see if we can figure it out what went wrong
13
week913 Odd Character Substitution Understanding the problem Devising a plan Have we done anything in the past that may help us with this? Is there any previously written code that we can re-use? Carrying out the plan Looking back (testing solution)
14
week914 A Buggy Approach int b int a String x String z String y String c start10(param) computer x.substring(0, b) c x.substring(a, b) c “” begin loop (x.length() - z.length() >= 1) (x.length() - z.length() >= 1) …DONE
15
week915 What happened? What was the error with the code? What else did we notice about the code that could have been better?
16
week916 Problem Solving So far we have looked at problem solving at the method level What about at the higher levels? The Object level The Project level (multiple objects)
17
week917 Project Level Problem Solving Program/project level: HIGHEST level Essentially making a model, deciding what parts are related What are the key components of this problem? What kind of information needs to be known? What objects do you need to do the task? How do they interact? Where is your key data going to be stored?
18
week918 Problem Solving Lay out the big picture (high level design) Break that into objects (object level design) Break each object into components (method level design)
19
week919 Sudoku Task Represent programmatically Sudoku Understanding the problem Devising a plan Carrying out the plan Looking back (testing solution)
20
week920 APCS-AB: Java Arrays (related information in Chapter 7 of Lewis & Loftus) November 2, 2005
21
week921 Homework Preview One Dimensional Arrays: Lights Out! Maybe a grade program with analysis For practice…before moving on to… Two Dimensional Arrays: Sudoku
22
week922 Grouping objects Fixed-sized collections When you know in advance how many items will be stored in a collection (and that stays fixed for the life of the collection) A fixed-sized collection is an array It’s kind of like a tray of cups – each cup can hold an object or a primitive data type Note: the array itself is an object Flexible-sized collections When you don’t know in advance how many items you will need to store Will go into more details about these in a few weeks
23
week923 Arrays An array is a group of variables (called elements or components) containing values that all have the same data type To refer to a particular element in an array, use the array’s name and the position number of the element in the array 54 32 2 9 4 3453 34 3 -423 int array called c c[0] c[3] c[4] c[5] c[6] c[7] c[8] c[1] c[2]
24
week924 Anatomy of an array Array names are the same as any other variable name An array with 9 elements (or variables) First element has index zero (the zeroth element) ith element of array c is c[i -1] Index must be a positive integer (or an integer expression that can be promoted to an int) 54 32 2 9 4 3453 34 3 -423 int array called c c[0] c[3] c[4] c[5] c[6] c[7] c[8] c[1] c[2]
25
week925 Advantages to using arrays It is easy to access individual items in an array (and it’s efficient) Arrays are able to store objects or primitive type values (int, double, float, etc) (We’ll see later that the flexible-sized collections can only store objects)
26
week926 Declaring and creating arrays Array objects occupy space in memory. All objects in Java must be created with a keyword new When you declare an array you must tell Java the type of the array elements and the number of the elements that will appear in the array Example declaration for an integer array called hourArray: int hourArray[] = new int[24]; // declares and creates an array to hold 24 int elements
27
week927 An array hourArray 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 :int[ ]
28
week928 How do we fill an array? All values are initially set to zero/null when we initialize an array One way to fill the array is to use an array initializer, a comma- separated list of expression enclosed in braces: when you declare it int n[] = {10, 23, 34, 235, 234}; The array length is automatically determined by the number of elements in the initializer list
29
week929 Class Exercise Write code to declare and initialize an array to hold the months of a year Write code to declare and initialize an array to hold the number of days in each month of the year
30
week930 How else do we fill an array? Arrays and for-loops go together like peanut butter and jelly! We could use a for loop and access each array element to set a value to it: int myArray = new int[10]; for(int i =0; i < myArray.length; i++){ myArray[i] = 5 * i; } Note: unlike the String class when we access the length of the array we are not calling a method, rather we are accessing one of the array’s instance variables
31
week931 Exercise Suppose we wish to print out the names and lengths of each of the months
32
week932 Mistakes It is not uncommon to make a programming mistake that causes the bounds of a loop to be mis-defined and the loop index variable to stray beyond the range of the array. For example, what if in your for loop you wrote: for(int i = 0; i <= array.length; i++){ System.out.println(array[i]); }
33
week933 Passing data to methods We’ve all passed values to methods to be used in calculation (parameters) We’ve returned item back from methods But how does this all work?
34
week934 Pass by Value When we pass an argument by value to a method, a copy of the argument’s value is made and passed to the called method public void method1(){ int x = 5; System.out.println(“X is: “ + x); method2(x); System.out.println(“X is: “ + x); } public void method2(int param){ param = 20; }
35
week935 Pass by Value x int int x = 7; 00000111 Declare an int value and assign it the value ‘7’. The bit pattern for 7 goes into the variable named x. z int void go(int z) { }Declare a method with an int parameter named z. x int 00000111 z int 00000111 Copy of x Call the go() method, passing the variable x as the argument. The bits in x are copied, and the copy lands in z. go(x);
36
week936 Pass by reference When we pass by reference, the caller gives the called method the ability to access the caller’s data directly and possibly modify that data (it is not copied) -- Basically a pointer (the address) to the object is given to the method public void method1(){ int array[] = {1, 2, 3, 4, 5}; //print array – what would it show method2(array); //print array – what would it show? method3(array[2]); //what is array[2] before this call? After it? } public void method2(int param[]){ for(int i = 0; i< param.length; i++){ param[i] *=2; } public void method3(int element){ element *= 4; }
37
week937 Pass by reference hourArray 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 :int[ ] array2 int hourArray = new int[24]; changeArray(hourArray); void changeArray(int array2[]) { } Ptr is copied
38
week938 Creating an array of objects Dog pets[ ]; //declare a Dog array variable pets = new Dog[7]; //create the array note, we have an array of Dog references, but no actual Dog objects! Need to make the Dog objects… pets[0] = new Dog(“Fido”); pets[1] = new Dog(“Goldy”);
39
week939 The pets array 0 1 2 3 4 5 6 7 Fido Goldy pets What does pets[0].bark(); do?
40
week940 And Now… Entering Multiple Dimensions!
41
week941 2D arrays Used to represent tables of values in rows and columns 0 12 3 45678 0 1 2
42
week942 2d arrays in Java Actually are one-dimensional arrays whose elements are also one-dimensional arrays Usually referred to as rows by columns So the example from the last slide is a 3-by-9 array To refer to an element is: a[row][col]
43
week943 Array Initializers for 2d arrays int b [ ][ ] = { {1,2}, {3,4}} Grouped by rows in braces int b [ ] [ ] = {{ 1, 2}, { 3, 4, 5}} Creates an array with a row of two elements and a row of three elements Row 0 is a 1-d array with two elements Row 1 is a 1-d array with three elements 01 0 1 12 34 01 0 1 12 34 5
44
week944 Array-Creation Expressions To create a square array: int b[ ] [ ]; b = new int [3] [4]; To create an array in which each row has a different number of columns: int c [ ] [ ]; c = new int[2][]; //create 2 rows c[0] = new int [5]; // row 0 has 5 columns c[1] = new int [3]; // row 1 has 3 columns
45
week945 And remember: for loops and arrays go together! For a 2d array, we will need nested for loops: for(int row = 0; row < array.length; row++){ for(int col = 0; col < array[row].length; col++){ System.out.print(array[row][col] + “ “); } System.out.println(); }
46
week946 Homework One Dimensional Arrays: Lights Out! Maybe a grade program with analysis Two Dimensional Arrays: Sudoku
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.