1 / 29

How do you do the following?

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:.

burroughss
Download Presentation

How do you do the following?

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. Java: Arrays 12/7/2018

  3. 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.

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

  5. 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 Address, subscript, index

  6. 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 Address, subscript, index

  7. 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.

  8. Indices (cont’d) • We can use as an index an int variable or any expressionthat evaluates to an int value. For example: a [3] a [k] a [k - 2] a [ (int) (6*Math.random()) ]

  9. 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).

  10. 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]; 1000 times!

  11. 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!

  12. Vocab. Check. • Array • Index • Element • Primitive • Subscript • ArrayIndexOutOfBoundsException

  13. 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" }; The right side creates what is being pointed to, referred to, … The left side creates the pointer, reference, object

  14. 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

  15. 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

  16. Review • An array.. • 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?

  17. 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};

  18. 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().

  19. 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.

  20. 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? What do you recall about…

  21. 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

  22. Sample Solution

  23. 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 }; for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+ " "); System.out.println(); gasPrices = new double[ ] { 4.0, 3.64, 2 , 12}; for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+" "); System.out.println();

  24. 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(); • }

  25. 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;

  26. 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.

  27. Sample Code initializing the vlaues. Note: You do not have to include the ‘new’ line. The compiler counts the initializers and sets this up for you! // 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

  28. 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.

More Related