CS-9 Computer Programming Fundamentals Arrays int a = new int[]; Instructor: Joel Castellanos e-mail: joel@unm.edu And in such indexes, although small pricks To their subsequent volumes, there is seen The baby figure of the giant mas Of things to come at large. --William Shakespeare, Troilus and Cressida //6 Textbook & Reading Assignment Introduction to java Programming ( th Edition) by Y. Daniel Liang Read by Wednesday: Sept 8 Chapter 7: Arrays Sections through. Study Questions: 7., 7.6, 7.7, 7.8, 7. Read by Friday: Sept Chapter 7: Arrays Sections 6 through end of chapter.
An Index (plural: indexes) In publishing, an index is a list of words or phrases, "headings", and associated pointers "locators" to where useful material relating to that heading can be found in a document. In a traditional back-of-the-book index, the headings will include names of people, places and events, and concepts selected by a person as being relevant and of interest to a possible reader of the book. The pointers are typically page numbers, paragraph numbers or section numbers. In a library catalog the words are authors, titles, subject headings, etc., and the pointers are call numbers. The Array 4 In Java, an array is collection of data items allocated in sequential memory locations that can be selected by indices computed at run-time. ) int[] a; ) int[] b = {,,,, }; ) int[] c = new int[]; 4) c[767] = 9; ) a = b; 6) System.out.println(a[i]); No matter how large an array, a particular element can be loaded or stored in constant time. a b c
Arrays: Fibonacci Series ) //Example without an array ) int f = ; ) int f = ; 4) int f = f + f; ) int f = f + f; 6) int f4 = f + f; 7) int f = f4 + f; 8) int f6 = f + f4; 9) ) System.out.println(f + " " + f + " " ) + f + " " + f + " " + f4 + " " + f ) + " " + f6); ) 4) // 8 Arrays: Fibonacci Series 6 ) //Example with an array ) int[] f = new int[7]; ) f[] = ; 4) f[] = ; ) f[] = f[] + f[]; 6) f[] = f[] + f[]; 7) f[4] = f[] + f[]; 8) f[] = f[4] + f[]; 9) f[6] = f[] + f[4]; ). int[] f declares f as a reference to an int array.. f = new int[7] reserves memory for 7 int variables and sets f to reference that block of memory. ) System.out.println(f[] + " " + f[] ) + " " + f[] + " " + f[] + " " + f[4] ) + " " + f[] + " " + f[6]); 4) // 8
Array Versatility: Fibonacci Series 7 ) //Example array In Java, arrays ) int[] f = new int[4]; hava a field ) f[] = ;.length not a method 4) f[] = ;.length(). ) for (int i=; i<f.length; i++) 6) { f[i] = f[i-] + f[i-]; By contrast, a 7) } String has a 8) method.length() not 9) for (int i=; i<f.length; i++) a field.length. ) { System.out.print(f[i] + " "); ) } ) System.out.println(); ) 4) // 8 4 89 44 77 Quiz: Arrays and Fibonacci Series In the Java code below, which lines can be swapped (have their positions interchanged) without causing an error or changing the output? ) int[] f = new int[6]; ) f[] = ; ) f[] = ; 4) for (int i=; i<f.length; i++) ) { 6) System.out.println(f[i-]); 7) f[i] = f[i-] + f[i-]; 8) } 8 a) & b) & 4 c) 4 & d) 4 & 6 e) 6 & 7 4
Helper Method: printarray ) public static void printarray(int[] array) ) { ) System.out.print("{ "); 4) for (int i=; i<array.length; i++) ) { 6) System.out.print(array[i] +" "); 7) } 8) System.out.println("}"); 9) } Why make this public? 9 Quiz: find max ) int[] numlist = {,,,,, }; ) ) int max = numlist[]; 4) for (int i=; i<numlist.length; i++) ) { if (numlist[i] > max) 6) { System.out.print(max+" "); 7) max=numlist[i]; 8) } 9) } ) System.out.println(); max= max = max= What is the output of the above code segment? a) b) c) d) e)
Find The Syntax Error ) int[] numlist = {,,,,, }; ) ) int max = numlist; 4) Type mismatch: Cannot Convert form int[] to int ) 6) for (int i=; i<numlist.length; i++) 7) { 8) if (numlist[i] > max) 9) { ) System.out.print(max+" "); ) max=numlist[i]; ) } )} 4)System.out.println(); Quiz: find max ) int[] numlist = {, 7,, 7, 8}; ) ) int max = numlist[]; 4) for (int i=; i<numlist.length; i++) ) { System.out.print(i + "(" +max+") "); 6) if (numlist[i] > max) 7) { max=numlist[i]; 8) } 9) } ) System.out.println(); What is the output of the above code segment? a) () (7) () (7) 4(8) b) () (7) () 4(7) (8) c) () (7) () 4(8) d) () () () 4(7) e) () () () 4() 6
Array Reference Copy ) public static void main(string[] args) ) { int[] a = {,,,, }; ) int[] b = a; 4) b[] = ; ) System.out.println( 6) a[] + ", " + a[] + ", " + b[]); 7) } Line Line Line 4 a a b a b Array Element Copy 4 ) public static void main(string[] args) ) { int[] a = {,,,, }; ) int[] b = new int[]; 4) for (i=; i<a.length; i++) ) { b[i]=a[i]; 6) } 7) b[] = 8; 8) System.out.println( 9) a[] + ", " + a[] + ", " + b[]); ) } a b a b 8 7
Quiz: Array Copying. public static void main(string[] args). { int[] a = {,,,,, 8};. int[] b = a; 4. b[] = 7;. System.out.println( 6. a[] + ", " + a[] + ", " + b[]); 7. } The output is: a) 7, 7, 7 b), 7, 7 c),, 7 d),, 7 e),, Allocating Space for Arrays of Objects 6 ) //Allocates space for three -bit integers. ) int[] x = new int[]; ) 4) //Allocates space for three references. ) JFrame[] frames = new JFrame[]; 6) 7) for (int i = ; i<; i++) 8) { 9) x[i] = i; ) JFrame constructor NOT called. JFrame constructor IS called. ) //Create each of the JFrame instances. ) p[i] = new JFrame(); ) frames[i].setbounds(i*,i*,, ); 4) frames[i].setvisible(true); ) } Without line, line will cause a Null Pointer Exception. 8
7 Comparing Array References. public static void main(string[] args). { int[] a = {,,,, 7};. int[] b = {,,,, 7}; 4. if (a==b). { System.out.println("yes"); 6. } 7. else System.out.println("no"); 8. } Output: no a 7 b 7 Quiz: On Which line is the Syntax Error? public class SyntaxQuiz { public static double abs(double a) { if (a <.) return -a; return a; } 8 public static void main(string[] args) { double[] x = {., -.4, 7.}; int i = ; a) System.out.println(abs(x[])); b) System.out.println(abs(x[i])); c) System.out.println(abs(x)); d) System.out.println(abs(i)); e) System.out.println(abs(x[] - x[])); } } 9
BouncingLines 9 ) Start with BouncingLine.java. ) BouncingLine.java uses int x, y, x, y to maintain the location of the line's two endpoints. ) Transform BouncingLine.java to use arrays int[] x, y, x, y to maintain a history of the line's endpoints. 4) After drawing NUM_LINES, each time step, erase the oldest line in the history and replace it with the line's new location. BouncingLines: imports ) import java.awt.color; ) import java.awt.graphics; ) import java.awt.event.actionevent; 4) import java.awt.event.actionlistener; ) import java.util.random; 6) import javax.swing.timer;
BouncingLines: Class and Instance Fields ) public class BouncingLines implements ActionListener ) { ) private Random rand = new Random(); 4) private Timer mytimer; ) private Picture mypic; 6) private Graphics canvas; 7) 8) private static final int DRAW_WIDTH = 6; 9) private static final int DRAW_HEIGHT = 6; ) private static final int NUM_LINES = ; ) ) private int[] x = new int[num_lines]; ) private int[] x = new int[num_lines]; Parallel 4) private int[] y = new int[num_lines]; Arrays ) private int[] y = new int[num_lines]; 6) private int curidx = ; 7) 8) private int speedx, speedx, speedy, speedy; Data Structure: Circular, Parallel Arrays private int[] x = new int[num_lines]; private int[] x = new int[num_lines]; private int[] y = new int[num_lines]; private int[] y = new int[num_lines]; 4 6 7 8 9 x y x y Newest line Oldest Line curidx nextidx
BouncingLines: main public static void main(string[] args) { new BouncingLines(); } 4 BouncingLines: Constructor ) public BouncingLines() ) { ) mypic = new Picture(DRAW_WIDTH, DRAW_HEIGHT); ) canvas = mypic.getoffscreengraphics(); 4) canvas.setcolor(color.white); ) canvas.fillrect(,, DRAW_WIDTH, DRAW_HEIGHT); 6) mypic.settitle("bounding Lines"); 7) 8) x[] = rand.nextint(draw_width); 9) y[] = rand.nextint(draw_height); ) x[] = rand.nextint(draw_width); ) y[] = rand.nextint(draw_height); ) ) speedx = rand.nextint()-; 4) speedy = rand.nextint()-; ) speedx = rand.nextint()-; 6) speedy = rand.nextint()-; 7) 8) mytimer = new Timer(, this); // miliseconds 9) mytimer.start(); 4) }
BouncingLines: actionperformed ( of ) ) public void actionperformed(actionevent arg) ) { ) //Let nextidx be the index of the oldest line. ) int nextidx = (curidx+) % NUM_LINES; ) //Erase oldest line. 6) //Move newest line and store its endpoints at index where // the oldest line was stored. 7) //If next line is out of bounds in the horizontal direction, then // give it a random horizontal speed in the opposite direction. //If next line is out of bounds in the vertical direction, then // give it a random vertical speed in the opposite direction. 9) //Update the current line index. 9) //Draw the new line 99) } BouncingLines: actionperformed ( of ) ) public void actionperformed(actionevent arg) ) { ) //Let nextidx be the index of the oldest line. ) int nextidx = (curidx+) % NUM_LINES; 4) ) //Erase oldest line. 6) canvas.setcolor(color.white); 7) canvas.drawline(x[nextidx], y[nextidx], 8) x[nextidx], y[nextidx]); 6
BouncingLines: actionperformed ( of ) 6) //Move newest line and store its endpoints at index 6) // where the oldest line was stored. 6) x[nextidx] = x[curidx] + speedx; 6) y[nextidx] = y[curidx] + speedy; 64) 6) x[nextidx] = x[curidx] + speedx; 66) y[nextidx] = y[curidx] + speedy; 67) 68) 7 BouncingLines: actionperformed (4 of ) 7) //If next line is out of bounds in the horizontal direction, then 7) // give it a random horizontal speed in the opposite direction. 7) //If next line is out of bounds in the vertical direction, then 7) // give it a random vertical speed in the opposite direction. 74) if (x[nextidx] < ) speedx = rand.nextint()+; 7) if (y[nextidx] < ) speedy = rand.nextint()+; 76) 77) if (x[nextidx]>draw_width) speedx =-(rand.nextint()+); 78) if (y[nextidx]>draw_height) speedy=-(rand.nextint()+); 79) 8) 8) 8) if (x[nextidx] < ) speedx = rand.nextint()+; 8) if (y[nextidx] < ) speedy = rand.nextint()+; 84) 8) if (x[nextidx]>draw_width) speedx =-(rand.nextint()+); 86) if (y[nextidx]>draw_height) speedy=-(rand.nextint()+); 87) 8 4
BouncingLines: actionperformed ( of ) 9) //Update the current line index. 9) curidx = nextidx; 9) 9) //Draw the new line 94) canvas.setcolor(color.red); 9) canvas.drawline(x[curidx], y[curidx], 96) x[curidx], y[curidx]); 97) mypic.repaint(); 98) 99)} 9