How do you do the following?

Slides:



Advertisements
Similar presentations
Arrays I Savitch Chapter 6.1: Introduction to Arrays.
Advertisements

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
CS0007: Introduction to Computer Programming Introduction to Arrays.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
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.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
int [] scores = new int [10];
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Information and Computer Sciences University of Hawaii, Manoa
Array in C# Array in C# RIHS Arshad Khan
Arrays Chapter 7.
Computer Programming BCT 1113
Chapter 7 Part 1 Edited by JJ Shepherd
Chapter 5: Control Structures II
Loop Structures.
Arrays, 2-D Arrays, and ArrayList
User input We’ve seen how to use the standard output buffer
Repetition-Counter control Loop
Java Arrays. Array Object An array :a container object holds a fixed number of values of a single type. The length of an array is established when the.
Building Java Programs
CSC 142 Computer Science II
Arrays, For loop While loop Do while loop
Building Java Programs Chapter 7
Building Java Programs
Java Language Basics.
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.
int [] scores = new int [10];
Java Programming Arrays
Arrays in Java What, why and how Copyright Curt Hill.
Building Java Programs
Building Java Programs
Defining methods and more arrays
Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays
Module 4 Loops.
Cs212: Data Structures Computer Science Department Lecture 2: Arrays.
python.reset() Also moving to a more reasonable room (CSE 403)
Arrays ICS2O.
Arrays Chapter 7.
int [] scores = new int [10];
Announcements Lab 6 was due today Lab 7 assigned this Friday
Building Java Programs
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays in Java.
Building Java Programs
Suggested self-checks: Section 7.11 #1-11
Data Structures & Algorithms
CS1001 Lecture 14.
Building Java Programs
Building Java Programs
Random Numbers while loop
Arrays.
Presentation transcript:

How do you do the following? Store the top 20 scores from a game? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include the following Vocabulary Ideas Examples Questions

Java: Arrays 12/7/2018

Objectives: Understand arrays and when to use them. Understand the vocabulary and syntax associated with using arrays. Be able to program using an array of primitives. This material, except 2-D arrays, is in the A-level AP subset.

When to use Arrays Large group of similar information. Use the information more than once. Sorting Tallying, i.e. elections

Address, subscript, index What is an Array? An array is a block of consecutive memory locations that hold values of the same data type. Individual locations are called array’s elements. When we say “element” we often mean the value stored in that element. element There is indeed some confusion in the usage of “element.” In some situations, the word refers to the location in an array, as in “set the value of the k-th element.” In other situations it refers to a value stored in the array, as in “find the smallest element.” This dual usage is somewhat similar to the situation with the term “variable.” This is no big deal, as long as everyone understands the difference between a location and a value stored in it. Address, subscript, index

What is an Array (cont’d) Rather than treating each element as a separate named variable, the whole array gets one name. Specific array elements are referred to by using array’s name and the element’s number, called index or subscript. element The idea is not to save names, of course, but to be able to handle an array’s elements uniformly, using algorithms. Address, subscript, index

Indices, Subscripts, addresses In Java, an index is written within square brackets following array’s name (for example, a[k]). Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n-1]. An index can have any int value from 0 to array’s length - 1. The convention of starting indices from 0 comes from C. It is easy to get used to.

Indices (cont’d) We can use as an index an int variable or any expression that evaluates to an int value. For example: a [3] a [k] a [k - 2] a [ (int) (6*Math.random()) ] That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms.

Indices (cont’d) In Java, an array is declared with fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws ArrayIndexOutOfBoundsException if an index is negative or if it is greater than the (length of the array – 1). arr = new int[newSize]; does not really resize arr: it simply throws away the old array and allocates a new one filled with default values. “Throws an exception” means reports a run-time error with rather detailed information about where in the code it occurred and then aborts the program.

Why Do We Need Arrays? The power of arrays comes from the fact that the value of a subscript can be computed and updated at run time. No arrays: With arrays: int sum = 0; sum += score0; sum += score1; … sum += score999; int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; Without arrays it would be difficult to process a collection of items algorithmically. Difficult but possible: with linked lists (Chapter 20). 1000 times!

Why Arrays? (cont’d) Arrays give direct access (random access) to any element — no need to scan the array. No arrays: With arrays: if (k == 0) System.out.print (score0); else if (k == 1) System.out.print(score1); else … // etc. System.out.print(scores[k]); 1000 times! “Direct access” means you can go directly to where the item is stored (like a particular track on a CD), as opposed to scanning from the beginning to find an item (as on a tape).

Vocab. Check. Array Index Element Primitive Subscript ArrayIndexOutOfBoundsException

Declaration/Initialization An array can be declared and initialized in one statement. For example: int [ ] scores = new int [10] ; double [ ] gasPrices = { 3.05, 3.17, 3.59 }; String [ ] words = new String [10000]; String [ ] cities = {"Atlanta", "Boston", "Cincinnati" }; Nothing new here: this is true for any object. The right side creates what is being pointed to, referred to, … The left side creates the pointer, reference, object

Declaration and Initialization When an array is created, space is allocated to hold its elements. If a list of values is not given, the elements get the default values. For example: length 10, all values set to 0 int [] scores; scores = new int [10] ; String [] words; words = new String [10000]; length 10000, all values set to null As for fields: 0 for numbers, false for booleans, null for objects. The elements get default values even if an array is a local variable. You can think of an array’s elements as sort of like its “fields.”

Initialization (cont’d) Otherwise, initialization can be postponed until later. For example: Not yet initialized String [ ] words; ... words = new String [ input.nextInt() ]; double[ ] gasPrices; … gasPrices = new double[ ] { 3.05, 3.17, 3.59 }; Not yet initialized If you try to use an unititialized array, (for example, arr.length or arr[k]), you will get a NullPointerException. The second initialization form (for gasPrices) is not in the AP subset.

Review An array.. What are some pros and cons of arrays? Holds a large group of similar information When you need to use the information more than once When you are sorting What are some pros and cons of arrays?

Your turn to declare Declare arrays to store the following The names of 15 people The gpas for each person The scores of 10, 15, -8, and 14 String [ ] names = new String [15] ; double [ ] gpas = new double [15]; int [ ] scores = {10, 15, -8, 14};

Array’s Length The length of an array is determined when that array is created. The length is either given explicitly or comes from the length of the {…} initialization list. The length of an array arrName is referred to in the code as arrName.length. length is a public field (not a method) in an array object. That is why it is not arrName.length(). As opposed to String, where length() is a method.

Initializing Elements Unless specific values are given in a {…} list, all the elements are initialized to the default value: 0 for numbers, false for booleans, null for objects. If its elements are objects, the array holds references to objects, which are initially set to null. Each object-type element must be initialized before it is used. It is important to understand this two-step process for initializing an array of objects: first you create the array object as a whole; then you initialize each element.

What do you recall about… Arrays Index Address ArrayIndexOutOfBoundsException Can the size of an array change? What does this line of code do? double [ ] gpas = new double [15]; How can you find the number of elements in an array?

Your turn, in BlueJ Declare arrays to hold the following Ten ages The names: Mannie, Moe, Jack and Curly 5 Radio stations Possible answers int [] ages = new int [10]; String [] names = {“Mannie”, “Moe”, “Jack”, “Curly”}; double [] stations = new double[5]; In BlueJ, Write the code to input values into the ages array. Write the code to display the information from the ages array

Sample Solution

What do these line of code do? double [ ] gasPrices = { 3.05, 3.17, 3.59 }; for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+ " "); System.out.println(); gasPrices = new double[ ] { 1, 5.9 }; gasPrices = new double[ ] { 4.0, 3.64, 2 , 12}; System.out.print(gasPrices[i]+" "); This will change where gasPrices is pointing. First to an array of 3 elements, then 2 elements, then 4 elements.

How can you… Create an integer array called scores that will hold 10 scores? int [] scores = new int[10]; What is the code to get the scores from the user? Scanner input = new Scanner(System.in); for (int count = 0;count < 10; count++) { System.out.println(“Enter a score.”); scores[count] = input.nextInt(); }

How can you … Find the average of the array declared previously? int total = 0; for (int count =0; count<scores.length;count++) total+=scores[count]; double average = 1.0*total / scores.length;

Sample Array Code Can also int [] anArray = new int[10]; To both declare and create. public class ArrayDemo { public static void main(String[] args) int [] anArray; // declare an array of integers anArray = new int[10]; // create the array // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) anArray[i] = i; System.out.print(anArray[i] + " "); } System.out.println(); Notice the addresses go from 0 to 9, anArray.length returns the number of values in the array.

Sample Code initializing the vlaues. // Fig. 7.3: InitArray.java // Initializing the elements of an array with an array initializer. public class InitArray { public static void main( String args[] ) // initializer list specifies the value for each element int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); } // end main } // end class InitArray Note: You do not have to include the ‘new’ line. The compiler counts the initializers and sets this up for you!

Program options Input: 10 scores Output: The number of scores within 10 points of the average of the 10 scores. (You’ll need to calculate the average before going back and seeing which scores are within 10 points of the average.) Create a random restaurant selection generator using an array to store the restaurant options. Using a while loop (so the user can be try again if they do not like the computers suggestion) have the computer display one of at least 5 random restaurants each time the user would like.