Presentation is loading. Please wait.

Presentation is loading. Please wait.

Last Time Math class Style and Documentation Loops And Exercises!

Similar presentations


Presentation on theme: "Last Time Math class Style and Documentation Loops And Exercises!"— Presentation transcript:

1 Last Time Math class Style and Documentation Loops And Exercises!
Spring 2006 CISC101 - Prof. McLeod

2 Announcements Lecture exercise sample solutions for last lecture are posted. Any questions on these? We should have a midterm next week – how about Tuesday the 23rd? One hour tutorial followed by 2 hrs for exam? Optional: bring a copy of Java syntax summary sheet. All topics up to and including arrays. Spring 2006 CISC101 - Prof. McLeod

3 Today “Warm-up” exercise to review loops.
Arrays – One dimensional and two dimensional. Please read array notes linked off of Syllabus page. More exercises (of course)! Introduction to class structure: Attributes Methods Spring 2006 CISC101 - Prof. McLeod

4 Warm Up! Print out the numbers between 0 and 200, inclusive, by 20’s, one number per line. Write the program three ways – using each type of loop, in turn. Spring 2006 CISC101 - Prof. McLeod

5 Warm Up – Cont. You could get the same output without using a loop, but what a pain! Suppose you had to count to 2,000 instead? You can write this program in a very inefficient way! Spring 2006 CISC101 - Prof. McLeod

6 Aside - Efficient Code We have talked about coding style and documentation. The compiler does not care about how efficient your code is either. Who does care? “Efficiency” is all about execution time: Try to write code that accomplishes your purpose with the minimum number of instructions, provided you have not greatly compromised the readability of your program. Spring 2006 CISC101 - Prof. McLeod

7 Aside – Memory Efficiency?
These days our computers have so much RAM, we are not so concerned about being memory efficient. But: Declaring an excess number of variables makes your program harder to read, as well as using up excess memory. Overly large programs are also harder to debug – Modular coding can lead to more efficient code that is also easier to write, debug and re-use. Spring 2006 CISC101 - Prof. McLeod

8 One-Dimensional Arrays
An array is just a collection of items, stored in computer memory (RAM). In Java: The items must all be of the same base type. Can be of any primitive type or object. The size of the array must be declared before any items can be stored. The size of the array cannot be changed after declaration. An array occupies a contiguous memory space. Array elements are numbered from zero. Spring 2006 CISC101 - Prof. McLeod

9 One-Dimensional Arrays - Cont.
The use of arrays in memory offers great speed advantages over processing data in and out of files. File operations are always much slower than operations dealing only in RAM. Typically, you will write array programs to: Read values from a file. Carry out all the calculations and manipulations required, in memory. Save the data back to another file. Arrays make it much easier to carry out the same calculation on many values. Spring 2006 CISC101 - Prof. McLeod

10 One-Dimensional Arrays - Declaration
For example, to create an array to hold 10 integers: int[] testArray = new int[10]; testArray now points to an area of memory that holds locations for 10 integers. It also points to one location that holds testArray.length which is an attribute of the array, that is equal to the number of elements. Arrays are Objects in Java. Spring 2006 CISC101 - Prof. McLeod

11 Aside – New Java Keywords?
The declaration and use of arrays does not require us to learn any new Java keywords. The only new thing are the square brackets [ ]. Spring 2006 CISC101 - Prof. McLeod

12 One-Dimensional Arrays - Declaration, Cont.
0480ff 0180ff int[] testArray 0480ff As a “pointer”, testArray points to an area of memory that contains a series of int values as well as the attribute length. 10 .length Spring 2006 CISC101 - Prof. McLeod

13 One-Dimensional Arrays - Declaration, Cont.
The java statement above can be split into two: int[] testArray; testArray = new int[10]; The first statement creates a variable of type int[] - that is to say that it will be an array of int’s. The variable, testArray is now an object of type int[] that contains an “object reference” or a pointer. The object reference is null after the first statement. Spring 2006 CISC101 - Prof. McLeod

14 One-Dimensional Arrays - Declaration, Cont.
int[] testArray; testArray = new int[10]; The second statement looks for a chunk of memory big enough to contiguously hold 10 integers (about 40 bytes), and then changes the object reference of testArray from null to the memory location of the chunk. This assignment of the object reference of the testArray object is carried out by the “=“ assignment operator. The new keyword is responsible for blocking out the memory space and initializing each memory location to the default value for a new memory location of type int (zero). Spring 2006 CISC101 - Prof. McLeod

15 One-Dimensional Arrays - Cont.
Back to the 10 array elements in memory: testArray[0] testArray[1] testArray[2] testArray[3] testArray[4] testArray[5] testArray[6] testArray[7] testArray[8] testArray[9] testArray.length 10 Spring 2006 CISC101 - Prof. McLeod

16 One-Dimensional Arrays - Indices
The numbers 0 to 9 are called the index values of the array. The notation used above allows you to refer to individual elements. Note that the elements of the array are numbered from zero. arrayname.length returns the number of elements in the array. length is an attribute of the array Object. Spring 2006 CISC101 - Prof. McLeod

17 One-Dimensional Arrays - Cont.
for loops are often used with arrays. For example, to initialize each of the elements of testArray to the value 1000 * i: int i; for (i = 0; i < 10; i++) testArray[i] = 1000 * i; Arrays can also be initialized at declaration, using an “array initializer”. To get the same array as above: int[] testArray = {0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000}; Spring 2006 CISC101 - Prof. McLeod

18 One-Dimensional Arrays - Cont.
Arrays can also be created using a variable (or constant) to specify the array size: final int MAX_SIZE = 1000; int[] testArray = new int[MAX_SIZE]; int size = testArray.length; // size is 1000 Spring 2006 CISC101 - Prof. McLeod

19 One-Dimensional Arrays - Cont.
All the examples so far, have been arrays of int’s. Could be arrays of double’s, boolean’s or even String’s: (anything in fact, as long as all the array elements are the same “thing”) For example (on the next slide): Spring 2006 CISC101 - Prof. McLeod

20 More Declaration Examples
double[] dArray = new double[50]; String[] sArray = new String[100]; String[] sArray2 = {“Hi”, “Ho”, “Silver!”}; Note that there is some flexibility in where the first set of “[]” goes. These two declarations are equivalent: double[] disNDat = new double[1000]; double disNDat[] = new double[1000]; Spring 2006 CISC101 - Prof. McLeod

21 One-Dimensional Arrays - “Out-of-bounds” Error
If n is the size of the array, then: Array indices (or “subscripts”) < 0 or  n are illegal, since they do not correspond to real memory locations in the array. These indices are said to be out-of-bounds. Reference to an out-of-bounds index produces an out-of-bounds exception, and the program will crash if the exception is not caught. Spring 2006 CISC101 - Prof. McLeod

22 One-Dimensional Arrays - “Out-of-bounds” Error, Cont.
Example: // Declare and initialize array int a[] = {1,2,3,4,5}; // Write array to screen (with an error!) for ( int i = 0; i <= 5; i++ ) System.out.println("a[" + i + "] = " + a[i]); On the screen: a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 a[4] = 5 java.lang.ArrayIndexOutOfBoundsException: 5 at TestBounds.main(TestBounds.java:15) Spring 2006 CISC101 - Prof. McLeod

23 One-Dimensional Arrays - Reminders
The “[]” brackets are used in three different ways, all associated only with arrays: At declaration: To specify the base type: int[] To specify the size: int[10] To refer to a single element: testArray[i] The base type of an array can be any primitive type, such as int, double, etc., as well as String, or any object type. Each array element must be of the same type. Spring 2006 CISC101 - Prof. McLeod

24 One-Dimensional Arrays - Reminders - Cont.
Remember that array elements are numbered starting from zero. So, the 10th element in an array called “myArray” is myArray[9]. Suppose myArray was declared to hold 1000 elements. If you try to access myArray[1000] you will get an “Array index out of bounds” error. Spring 2006 CISC101 - Prof. McLeod

25 Multi-Dimensional Arrays
Multi-dimensional arrays are just arrays of arrays. For example, to create a two-dimensional array: int[][] twoDArray = new int[10][20]; Holds 200 elements. Initialize each element to the sum of its indices, for example: int i, j; for (i = 0; i < 10; i++) for (j = 0; j < 20; j++) twoDArray[i][j] = i + j; Spring 2006 CISC101 - Prof. McLeod

26 Multi-Dimensional Arrays - Cont.
Everything is the same as for one-dimensional arrays, except that you have a set of “[]” for each dimension. Two-dimensional arrays are suitable for storage of a single type of data that would normally be viewed in a table with rows and columns. Java does not place any limitation on the number of dimensions used in an array. Spring 2006 CISC101 - Prof. McLeod

27 Multi-Dimensional Arrays - Cont.
Consider: int[][] exArray = new int[3][5]; 1002fc int[][] exArray 0480ff int[] exArray[0] 1002fc exArray[1] 1010fc exArray[2] 1201ab 1010fc 1201ab Spring 2006 CISC101 - Prof. McLeod

28 Multi-Dimensional Arrays - Cont.
So exArray points to three one dimensional arrays: exArray[0] exArray[1] exArray[2] Each of these arrays has the same length: exArray[2].length // returns 5 Spring 2006 CISC101 - Prof. McLeod

29 Multi-Dimensional Arrays - Cont.
int[][] twoDArray = new int[10][20]; The above is equivalent to: int[][] twoDArray; twoDArray = new int[10][]; for (int i = 0; i < 10; i++) twoDArray[i] = new int[20]; As shown above: twoDArray.length // gives 10 twoDArray[0].length // gives 20 Spring 2006 CISC101 - Prof. McLeod

30 Multi-Dimensional Arrays - Cont.
“Ragged Arrays” are not “square” and are legal in Java: int[][] raggedArray = new int[5][]; raggedArray[0] = new int[2]; raggedArray[1] = new int[4]; raggedArray[2] = new int[6]; raggedArray[3] = new int[8]; raggedArray[4] = new int[10]; Spring 2006 CISC101 - Prof. McLeod

31 Multi-Dimensional Arrays - Cont.
Array initializer for two-D array, for example: int[][] twoDArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; System.out.println(twoDArray.length); // 4 System.out.println(twoDArray[0].length); // 3 Spring 2006 CISC101 - Prof. McLeod

32 Time for An Exercise! Prompt the user for how many random numbers to generate (using Math.random()). Exit the program (use System.exit(0);) if the user enters a number < 1. Generate and store these numbers in an array. Calculate the mean of the array of numbers. Count how many of these numbers are <= 0.5 . Display the mean and the count <= 0.5 and > 0.5. Spring 2006 CISC101 - Prof. McLeod

33 Array Exercise 2 Prompt the user for the number of columns and the number of rows of a 2D array. Both numbers must be > 2 (or just exit the program). Generate and then display a 2D array of this size with the number 8 all around the outside and 1 everywhere else. For example for 6 columns and 5 rows: 888888 811118 Spring 2006 CISC101 - Prof. McLeod

34 Arrays as Objects - Example
int[] first = {1, 2, 3, 4, 5}; int[] second = {10, 20, 30, 40, 50, 60, 70}; 1 2 3 4 5 10 20 30 40 50 60 70 0480ff 0960ff int[] first 0480ff int[] second 0960ff .length 5 .length 7 Spring 2006 CISC101 - Prof. McLeod

35 Arrays as Objects - Example Cont.
second = first; // Aliasing! 1 2 3 4 5 10 20 30 40 50 60 70 0480ff 0960ff int[] first 0480ff int[] second 0480ff .length 5 .length 7 Spring 2006 CISC101 - Prof. McLeod

36 Arrays as Objects - Example Cont.
// after garbage collection 1 2 3 4 5 0480ff int[] first 0480ff int[] second 0480ff .length 5 Spring 2006 CISC101 - Prof. McLeod

37 Arrays as Objects - Example Cont.
first[4] = 500; // second[4] is also 500 1 2 3 4 500 0480ff int[] first 0480ff int[] second 0480ff .length 5 Spring 2006 CISC101 - Prof. McLeod

38 Arrays as Objects - Aliasing
So, setting one array to equal another as in: array1 = array2; sets array1 to point to the same data memory location that was (and still is) pointed to by array2. Now, changing the value of an element in array2 will change that same element in array1, or visa-versa - this makes sense since both array Objects point to the same set of data values in memory! Spring 2006 CISC101 - Prof. McLeod

39 Arrays as Objects - Cont.
System.out.println() will print anything, but when it is used to print an Object, some interesting “gibberish” is produced! Testing Objects for equality (with the “==“ boolean operator) is also interesting: This test will only give a true when both objects have been aliased, using the assignment operator “=“. So, even if both arrays have identical contents, “==“ will return false, unless both arrays point to the same location. This means that comparing Objects with “==“ only compares pointers, not contents. Spring 2006 CISC101 - Prof. McLeod

40 System.out.println(array1 == array2);
Array Exercise 3 Using array literals, create two arrays, array1 holding the numbers 1, 2, 3, 4, 5 and array2 with the numbers 100, 200, 300. Use System.out.println(array1) to print out the first and then a similar statement to print out array2. Run the program. Add the line System.out.println(array1 == array2); and run again. Spring 2006 CISC101 - Prof. McLeod

41 System.out.println(array1 == array2);
Array Exercise 3, Cont. Add code to print out the first elements of both arrays, and run again. Add the line array1 = array2; System.out.println(array1 == array2); as above, and run again. Add or copy the code to print the first elements again, and run again. Explain the results. Change the first element of array1 to -500 and display both elements again. Spring 2006 CISC101 - Prof. McLeod

42 Array Exercise 4 Modify the program you wrote for exercise 2 to put zero’s on the diagonals. Spring 2006 CISC101 - Prof. McLeod

43 Class Structure A class consists of instance variables and/or methods.
By convention, instance variables are all declared before the methods: public class ShowStructure { // instance variables here // methods here } // end class ShowStructure Spring 2006 CISC101 - Prof. McLeod

44 Instance Variables Also called “class variables” or “attributes”.
These variables are declared at the same level as the methods in a class. They are known to all methods within a class. Their scope is the entire class in which they were declared. Spring 2006 CISC101 - Prof. McLeod

45 Instance Variables, Cont.
The syntax for the declaration of attributes: [private|public] [static] [final] type variable_name [= literal_value]; The “|” in this syntax means “one or the other”. The “[ ]” means that this part is optional. Spring 2006 CISC101 - Prof. McLeod

46 Instance Variables, Cont.
private or public determines if the attribute can be accessed from outside the class. A static attribute shares only a single memory location, regardless of how many times its class is instantiated. So, every instantiation shares this attribute, and any of them can change it. Otherwise, the declaration of an attribute is just the same as any other variable declaration. Spring 2006 CISC101 - Prof. McLeod

47 Methods The syntax for simple method declaration:
[private|public] [static] return_type method_name ([parameter_list]) {…} Spring 2006 CISC101 - Prof. McLeod

48 Methods - Cont. Often, “utility” methods that are only used by other methods within a class are kept private. When the “static” keyword is used with methods, it means that the method can be used without instantiation. (All the methods in the Math class are static, for example.) When a static method is invoked for the first time, it is loaded into memory and then will stay in memory until the program completes. Spring 2006 CISC101 - Prof. McLeod

49 Aside - “Instantiation”???
Simply put, it is the creation of a new Object using the “new” keyword. Another Object is required to provide the “pattern” for the new Object: Familiar example: Scanner input = new Scanner(System.in); Spring 2006 CISC101 - Prof. McLeod

50 Aside - “Instantiation”??? – Cont.
Another example: String aString = new String(“Hello class!”); is actually better form than: String aString = “Hello class!”; The latter form (aliasing aString to a String literal…) is allowed because it is convenient (and much like using primitive types.) Spring 2006 CISC101 - Prof. McLeod

51 Methods - Cont. A method must also have a return_type.
A return type is what the method will return. It can be any single Object or a primitive type. (For example: an int, double, String, an array, or any other pre-defined Object.) If the method does not return anything, then the keyword “void” is used instead. The main method does not return any value, so that’s why it is declared as in: public static void main (String[] args) {…} Spring 2006 CISC101 - Prof. McLeod

52 Methods - Cont. parameter_list provides a means of passing items, or parameters, into a method. It is optional. It can consist of one or many parameters, separated by commas. Each parameter type must be declared in the parameter list. Spring 2006 CISC101 - Prof. McLeod

53 Methods - Cont. Also important: Unless the return type is void, the method must contain at least one return statement. A void method can also use a return statement without anything after it, as a means of termination of the method. A method always stops (terminates) when a return statement is encountered. Syntax: return [literal|expression]; Spring 2006 CISC101 - Prof. McLeod

54 Methods - Cont. The type of “literal|expression” must match the return type specified in the method declaration statement. Spring 2006 CISC101 - Prof. McLeod

55 Method Examples public void printHello() {
System.out.println(“Hello”); } // end printHello public void printHelloName(String yourName) { System.out.println(“Hello “ + yourName); } // end printHelloName public void printAvg(int a, int b) { System.out.println((a + b) / 2.0); } // end printAvg Spring 2006 CISC101 - Prof. McLeod

56 Method Examples - Cont. public double average(double a, double b) {
return (a + b) / 2; } // end average public int lowest(int a, int b) { if (a <= b) return a; else return b; } // end lowest Spring 2006 CISC101 - Prof. McLeod

57 Aside - Methods in the Same Class as main
Since main is static, then any method it invokes that is declared in the same class as main, must also be declared static. (We’ll see lots of examples of this situation!) Spring 2006 CISC101 - Prof. McLeod

58 Methods - Cont. Why use methods? Modular design.
Avoids repetitious code. Independent testing of sub-tasks. Reusable code. Design and test a method once, and re-use it whenever you need to solve a similar problem. Isolation from unintended side effects. The only variables from the caller that can be seen from a method are those in the parameter list. Spring 2006 CISC101 - Prof. McLeod

59 Methods - Cont. Start thinking of your program as a collection of methods, where the main method only acts to call the other methods. The use of modular design techniques with methods is part of what is called “encapsulation”. Spring 2006 CISC101 - Prof. McLeod

60 Methods - Cont. When designing method operations, make sure a method only does one “thing”, do not combine operations (except in main). Concentrate on coding the individual methods, one at a time, when you write a program. If you have thought out the “code-level interface” between the methods, then the methods will be completely independent of each other. Try to minimize the size of the main method, if possible. However, if the main method is often going to be responsible for screen I/O - then more code may be necessary. Spring 2006 CISC101 - Prof. McLeod


Download ppt "Last Time Math class Style and Documentation Loops And Exercises!"

Similar presentations


Ads by Google