Building Java Programs

Slides:



Advertisements
Similar presentations
1 Various Methods of Populating Arrays Randomly generated integers.
Advertisements

Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
Arrays Pepper. What is an Array A box that holds many of the exact same type in mini-boxes A number points to the mini-box The number starts at 0 String.
1 Building Java Programs Chapter 2: Primitive Data and Definite Loops These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Building Java Programs Chapter 7
1 Building Java Programs Chapter 3: Introduction to Parameters and Objects These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They.
1 Array basics. Data Structures Sometimes, we have data that have some natural structure to them  A few examples: Texts are sequences of characters Images.
Array - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/19/20151.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
 2005 Pearson Education, Inc. All rights reserved Arrays.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Topic 21 arrays - part 1 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from "Should.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
CSc 110, Autumn 2016 Lecture 15: lists Adapted from slides by Marty Stepp and Stuart Reges.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Arrays Chapter 7.
Building Java Programs
Chapter 8 Multidimensional Arrays
CSCI 162 – Introduction to Programming II William Killian
[ 4.00 ] [ Today’s Date ] [ Instructor Name ]
© 2016 Pearson Education, Ltd. All rights reserved.
Dr. Kyung Eun Park Summer 2017
Building Java Programs
Building Java Programs
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
CSC 142 Computer Science II
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Building Java Programs
Arrays An Array is an ordered collection of variables
Building Java Programs Chapter 7
Building Java Programs
Defining New Types of Objects, part 3
Building Java Programs
Building Java Programs
Building Java Programs
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Lecture 15: lists Adapted from slides by Marty Stepp and Stuart Reges
Building Java Programs
Chapter 8 Multidimensional Arrays
Building Java Programs
Why did the programmer quit his job?
Building Java Programs
Can we solve this problem?
python.reset() Also moving to a more reasonable room (CSE 403)
Lecture 19: lists Adapted from slides by Marty Stepp and Stuart Reges
Arrays Chapter 7.
Lecture 9: Arrays Building Java Programs: A Back to Basics Approach
Lecture 10: Arrays AP Computer Science Principles
Dr. Sampath Jayarathna Cal Poly Pomona
Using Objects (continued)
Array basics Readings: 7.1.
Building Java Programs
Suggested self-checks: Section 7.11 #1-11
Can we solve this problem?
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Suggested self-checks:
Building Java Programs
File output; Arrays reading: 6.4 – 6.5, 7.1
Building Java Programs
Why are arrays useful? We can use arrays to store a large amount of data without declaring many variables. Example: Read in a file of 1000 numbers, then.
Can we solve this problem?
Building Java Programs
Suggested self-checks: Section 7.11 #12-29
How do you do the following?
Arrays.
Week 7 - Monday CS 121.
Presentation transcript:

Building Java Programs Chapter 7: Arrays Marty Stepp These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2005. They may not be rehosted, sold, or modified without expressed permission from the authors. All rights reserved.

Chapter outline Array basics Arrays for counting and tallying declaring and initializing an array getting and setting values of elements of an array limitations of arrays Arrays for counting and tallying Shifting elements in an array Advanced array usage arrays as parameters to methods String methods that use arrays Graphics methods that use arrays the Arrays class command-line arguments

suggested reading: 7.1 - 7.2.1, 7.4 - 7.5 self-checks: #1 - 11 Array basics suggested reading: 7.1 - 7.2.1, 7.4 - 7.5 self-checks: #1 - 11

A problem we can't solve (yet) Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44.57142857142857 4 days were above average. We need access to the temperatures once to compute the average, and then again to tell how many were above average.

Why the problem is tough We appear to need each input value twice: once to compute the average a second time to count how many were above average We could examine each value twice if we could read them into variables. However, we don't know in advance how many variables we'll need, because we don't know how many days' weather are coming until the program is running. We need a way to declare many variables' worth of memory in a single step.

Arrays array: A single variable that can store many values of the same type. element: One value in an array. index: A 0-based integer, which is used to access an element from an array. We usually draw an array as a row or column of boxes. Example: an array of ten integers index 1 2 3 4 5 6 7 8 9 value 12 49 -2 26 17 -6 84 72 element 0 element 4 element 9

Array declaration Declaring/initializing an array: <type> [] <name> = new <type> [ <length> ]; Example: int[] numbers = new int[10]; The length of the array is specified between [ ] brackets. The array's length can be any expression, such as a constant or variable's value. int x = 2 * 3 + 1; int[] numbers = new int[x % 5 + 2]; index 1 2 3 4 5 6 7 8 9 value

Array initial contents When arrays are initially constructed, every element has a 0-equivalent value. int: 0 double: 0.0 boolean: false char: '\0' (the "null character") String or other object: null (null means "no object") An array of integers An array of real numbers index 1 2 3 4 value index 1 2 3 value 0.0

Accessing array elements Assigning a value to an array element: <array name> [ <index> ] = <value> ; Example: numbers[0] = 27; numbers[3] = -6; Using an array element's value in an expression: <array name> [ <index> ] System.out.println(numbers[0]); if (numbers[3] < 0) { System.out.println("Element 3 is negative."); } index 1 2 3 4 5 6 7 8 9 value 27 -6

Out-of-bounds indexes The only indexes that are legal to access in an array are those in the range of 0 to the array's length - 1 Reading or writing any index outside this range will crash your program with an ArrayIndexOutOfBoundsException. Example: int[] data = new int[10]; System.out.println(results[0]); // okay System.out.println(results[-1]); // exception System.out.println(results[9]); // okay System.out.println(results[10]); // exception index 1 2 3 4 5 6 7 8 9 value

Arrays of other types Arrays can contain other types, such as double. Example: double[] results = new double[6]; results[2] = 3.4; results[5] = -0.5; boolean[] tests = new boolean[6]; tests[3] = true; index 1 2 3 4 5 value 0.0 3.4 -0.5 index 1 2 3 4 5 value false true

Accessing array elements A longer example of accessing and changing elements: int[] numbers = new int[8]; numbers[1] = 4; numbers[4] = 99; numbers[7] = 2; int x = numbers[1]; numbers[x] = 44; numbers[2] = 11; // use numbers[7] as index x 4 1 2 3 4 5 6 7 11 44 numbers

Arrays and for loops Arrays are very commonly used with for loops that pass over each element and process it in some way: Example (print each element of an array): for (int i = 0; i < 8; i++) { System.out.print(numbers[i] + " "); } Output (when used on array from previous slide): 0 4 11 0 44 0 0 2

More arrays and for loops Sometimes we assign each array element a value in a for loop. Example: for (int i = 0; i < 8; i++) { numbers[i] = 2 * i; } What values would be stored into the array after this code? numbers[i] = i * i; Notice that the code in the previous slides refers to the array's length of 8 many times. What's bad about this? index 1 2 3 4 5 6 7 value 8 10 12 14 value 1 4 9 16 25 36 49

The .length field An array has a field named .length that returns its total number of elements. General syntax: <array name> .length Notice that it doesn't have parentheses like a String's .length() . Example: for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); } Output: 0 1 4 9 16 25 36 49 What expression refers to the last element of the array? The middle element?

Can we solve it now? Let's examine a solution to the weather program now: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44.57142857142857 4 days were above average.

Weather program solution Solution to weather program, part 1: // prompt user for number of days Scanner console = new Scanner(System.in); System.out.print("How many days' temperatures? "); int numDays = console.nextInt(); // create array to store all days' temperatures int[] temps = new int[numDays]; int sum = 0; // read each day's temperature from the console, store it for (int i = 0; i < numDays; i++) { System.out.print("Day " + (i + 1) + "'s high temp: "); temps[i] = console.nextInt(); sum += temps[i]; } double average = (double) sum / numDays;

Weather program solution Solution to weather program, part 2: // count number of days' temperatures above average int above = 0; for (int i = 0; i < numDays; i++) { if (temps[i] > average) { above++; } // report results System.out.println(); System.out.println("Average temp = " + average); System.out.println("(" + above + " days above average)");

Arrays for counting and tallying suggested reading: 7.2.1

A multi-counter problem Imagine that we want to examine a large integer and count the number of occurrences of every digit from 0 through 9. Example: the number 229231007 contains two 0s, one 1, three 2s, one 7, and one 9. How can we do it? We need to examine each digit of the large integer and count how many times we've seen that digit. This will require counters for each of the values 0--9. We could declare 10 counter variables for this, or (preferred) we could use an array of size 10. The element with index i will store the counter for digit value i.

Creating an array of tallies The following code builds an array of digit counters: int num = 229231007; int[] counts = new int[10]; while (num > 0) { int digit = num % 10; counts[digit]++; num = num / 10; } You can watch the array build itself by running the code in the Jeliot Java program visualizer: http://www.cs.joensuu.fi/jeliot/index.php index 1 2 3 4 5 6 7 8 9 value

Histogram problem Given a file of integer exam scores, such as: 82 66 79 63 83 81 Write a program that will print a histogram of stars indicating the number of students who earned each unique exam score. 85: ***** 86: ************ 87: *** 88: * 91: **** Time permitting, try graphing the data with DrawingPanel.

Why are arrays useful? We can use arrays to store a large amount of data without declaring many variables. Example: Read in a file of 1000 numbers, then print out the numbers in reverse order. Arrays can help us to group related data into elements. Example: For a given school exam, open a file full of exam scores and count up how many students got each score from 0 through 100. Arrays let us hold on to data and access it in random order. Example: Read a file full of babies' names, store each name's data as an element in a large array, and then examine it later to find many names that the user types.