Download presentation
Presentation is loading. Please wait.
Published bySilvester Newton Modified over 6 years ago
1
Announcements Lab 6 was due today Lab 7 assigned this Friday
Assignment 4 due next Friday
2
Questions? Last time: Method signatures
3
Today in COMP 110 Array Basics Programming Demo
4
Recall from Lab 4 A program to read in a list of basketball scores from the user and output statistics System.out.println("Enter the list of basketball scores " + "(enter a negative number to end your list): "); while(score >= 0) { score = keyboard.nextInt()); totalGames++; scoreSum += score; } if (totalGames > 0) { double average = (double) scoreSum / (double) totalGames; System.out.println("Average score: " + average);
5
What if… …we wanted to know which of the scores entered were
Above average? Below average? How would we do it? Can only compute average after we have all scores We need to look at previous scores Let’s simplify this a little first
6
One Possibility… Assume Exactly 5 Scores
System.out.println("Enter 5 basketball scores:"); int score1 = keyboard.nextInt(); int score2 = keyboard.nextInt(); int score3 = keyboard.nextInt(); int score4 = keyboard.nextInt(); int score5 = keyboard.nextInt(); double average = (double) (score1 + score2 + score3 + score4 + score5) / 5.0; System.out.println("Average score: " + average); //repeat this for each of the 5 scores if(score1 > average) System.out.println(score1 + ": above average"); else if(score1 < average) System.out.println(score1 + ": below average"); else System.out.println(score1 + ": equal to the average");
7
What If We Had 80 Scores? System.out.println("Enter 80 basketball scores:"); int score1 = keyboard.nextInt(); int score2 = keyboard.nextInt(); int score3 = keyboard.nextInt(); // ...are we done yet? int score23 = keyboard.nextInt(); int score24 = keyboard.nextInt(); int score25 = keyboard.nextInt(); // ...how about now? int score67 = keyboard.nextInt(); int score68 = keyboard.nextInt(); // ...still going… int score80 = keyboard.nextInt(); // ...whew! double average = (double) (score1 + score2 + score3 + score score23 + score24 + score ) / 80.0; System.out.println("Average score: " + average); // now do below/above average check for all 80 scores
8
Arrays There’s a much easier way Use an array!
Like a list of variables, but with a convenient, compact way to name them A special kind of object in Java used to store a collection of data
9
Creating an Array int[] scores = new int[5]; This creates an array called “scores” that holds five integer values scores[0] scores[1] scores[2] scores[3] scores[4]
10
Indexing Variables such as scores[0] and scores[1] that have an integer expression in square brackets are known as: indexed variables, subscripted variables, array elements, or simply elements An index or subscript is an integer expression inside the square brackets that indicates an array element
11
Indexing Where have we seen the word index before?
String’s indexOf method Index numbers start with 0. They do NOT start with 1 or any other number.
12
Indexing Array elements can be used just like any other variable of the same type scores[3] = 68; scores[4] = scores[4] + 3; // just made a 3-pointer! System.out.println(scores[1]);
13
Vector Example double[] vector = new double[3]; //an array of 3 doubles (x, y, z) vector[0] = 1.; //set the x value vector[1] = 56.; //set the y value vector[2] = 101.; //set the z value //compute the length of the vector double length = Math.sqrt(vector[0]*vector [0] + vector [1]*vector [1] vector [2]*vector [2]); //normalize the vector double[] vectorN = new double[3]; vectorN[0] = vector[0]/length; vectorN[1] = vector[1]/length; vectorN[2] = vector[2]/length; (x,y,z)
14
Arrays The array itself is referred to by a name “scores” or “vector” (in our examples) Indices 1 2 3 4 68 73 57 102 94 the array scores scores[3]
15
Indexing The index (value in square brackets) does not have to a simple integer It can be an expression that evaluates to an integer int[] scores = new int[5]; //initialize all scores to 0 for(int index = 0; index < 5; index++) scores[index] = 0; for(int index = 0; index < 10; index++) scores[index/2] = 0;
16
Array Terminology scores[index/2] = 0; Indexed Variable Array name
17
Reading in Scores System.out.println("Enter 5 basketball scores:");
int[] scores = new int[5]; int scoreSum = 0; for(int i = 0; i < 5; i++) { scores[i] = keyboard.nextInt(); scoreSum += scores[i]; } double average = (double) scoreSum / 5; System.out.println("Average score: " + average); if(scores[i] > average) System.out.println(scores[i] + ": above average"); else if(scores[i] < average) System.out.println(scores[i] + ": below average"); else System.out.println(scores[i] + ": equal to the average");
18
Array Details Syntax for creating an array: Example: Alternatively:
Base_Type[] Array_Name = new Base_Type[Length]; Example: int[] pressure = new int[100]; //create 100 variables of type int that can //be referred to collectively Alternatively: int[] pressure; //declare an integer array called pressure pressure = new int[100]; //allocate memory for the array to hold 100 ints
19
Array Details The base type can be any type
double[] temperature = new double[7]; Student[] students = new Student[35]; Pet[] myPets = new Pet[3]; The number of elements in an array is its length, size, or capacity temperature has 7 elements, temperature[0] through temperature[6] students has 35 elements, students[0] through students[34] myPets has 3 elements, myPets[0] through myPets[2]
20
Use a Named Constant Use a named constant instead of an int literal when creating an array Good programming practice public static final int NUMBER_OF_READINGS = 100; int[] pressure = new int[NUMBER_OF_READINGS]; Poor programming practice int[] pressure = new int[100];
21
Use a Named Constant Why is it poor programming practice to use an int literal for the size? It can be error prone You may have to change multiple places in the code whenever you change the length of the array int[] pressure = new int[100]; for(int index = 0; index < 100; index++) scores[index] = 0;
22
Determining the Length
If you’re not sure what the length should be, consider reading it in from the keyboard System.out.println("How many scores?"); int numScores = keyboard.nextInt(); int[] scores = new int[numScores];
23
Array Length An array is a special kind of object
It has one public instance variable: length length is equal to the length of the array Pet[] pets = new Pet[20]; int sizeOfArray = pets.length; //sizeOfArray will have the value 20 You cannot change the value of length (it is final)
24
Our Previous Example System.out.println("Enter 5 basketball scores:"); int[] scores = new int[5]; int scoreSum = 0; for(int i = 0; i < scores.length; i++) { scores[i] = keyboard.nextInt(); scoreSum += scores[i]; } double average = (double) scoreSum / scores.length; System.out.println("Average score: " + average); if(scores[i] > average) System.out.println(scores[i] + ": above average"); else if(scores[i] < average) System.out.println(scores[i] + ": below average"); else System.out.println(scores[i] + ": equal to the average"); Better than using the value 5 everywhere because it’s not obvious where it comes from and its value may change!
25
For Loops and Arrays For loops are often perfectly suited to processing arrays Why? Because we know the number of iterations (array.length) int[] pressure = new int[100]; for(int index = 0; index < pressure.length; index++) scores[index] = 0;
26
Be Careful with Indices
Indices MUST be in bounds double[] entries = new double[5]; entries[5] = 3.7; //RUN-TIME ERROR! Index out of bounds Your code WILL compile with an out-of-bounds index But it will result in a run-time error (crash)
27
Crash if more than 10 scores are entered!
Out of Bounds Example System.out.println("Enter up to 10 scores"); System.out.println("End your input with a negative number"); int scores = new int[10]; Scanner keyboard = new Scanner(System.in); int currScore = keyboard.nextInt(); int i = 0; while(currScore >= 0) { scores[i] = currScore ; i++; number = keyboard.nextInt(); } Crash if more than 10 scores are entered!
28
Initializing Arrays You can initialize arrays when you declare them
int[] scores = {68, 97, 102}; Equivalent to int[] scores = new scores[3]; scores[0] = 68; scores[1] = 97; scores[2] = 102;
29
Exercise What is the output? int[] anArray = new int[10];
for(int i = 0; i < anArray.length; i++) anArray[i] = 2*i; System.out.println(anArray[i] + " "); Output
30
Arrays & Methods Arrays can be used with methods just like other objects can Arrays can be passed as arguments to methods Arrays can be returned from methods The main method takes in an array as an argument public static void main(String[] args) { … } An array of Strings
31
Arrays as Arguments Example //init all array elements to 0
public void initArray(int[] array) { for(int i = 0; i < array.length; i++) array[i] = 0; }
32
Returning Arrays Example
//create an array of the given size and return it public int[] createArray(int size) { int[] array = new int[size]; return array; }
33
Programming Demo ArrayUtils
Write a utility class with the following methods printArray - A method that prints an array of ints out to screen swap - A method that takes in an array and two indices a & b, whose locations in the array should be swapped sum – A method that sums all the elements in an array
34
Programming Demo Programming
35
Testing ArrayUtils Perform the following tests
Read in a number of integers specified by the user into an array and: Display the input entered by the user Display the sum of all integers entered by the user Display each integer with its contribution to the sum Swap the 1st and last elements of the array and display the altered array
36
Friday Recitation Bring Laptops (fully charged) Questions on Program 4
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.