Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.

Slides:



Advertisements
Similar presentations
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
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.
 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.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: File Output; Reference Semantics reading: , 7.1, 4.3, 3.3 self-checks:
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Java Unit 9: Arrays Declaring and Processing Arrays.
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)
Hello AP Computer Science!. What are some of the things that you have used computers for?
CSCI 1226 Fall 2014 Reviews Section B. Computers  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice,
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
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.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
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.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Types in Java 8 Primitive Types –byte, short, int, long –float, double –boolean –Char Also some Object types: e.g. “String” But only single items. What.
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.
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.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
CSE 110 Review Session Hans Hovanitz, Kate Kincade, and Ian Nall.
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.
CS 31 Discussion, Week 5 Faisal Alquaddoomi, Office Hours: BH 2432, MW 4:30-6:30pm, F 12:00-1:00pm (today)
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 5: ARRAYS ARRAYS. Why Do We Need Arrays? Java Programming: From Problem Analysis to Program Design, 4e 2  We want to write a Java program that.
int [] scores = new int [10];
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Review of CSCI 1226 What You Should Already Know.
Lecture 6: Methods MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture, you will learn… What a method is Why we use.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
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.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
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.
Chapter VII: Arrays.
4. Java language basics: Function
Chapter 7 User-Defined Methods.
Chapter 7 Part 1 Edited by JJ Shepherd
Arrays in C.
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
Building Java Programs Chapter 7
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.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
Building Java Programs
More Methods and Arrays
Arrays and Methods.
int [] scores = new int [10];
Building Java Programs
Suggested self-checks: Section 7.11 #1-11
Java Programming Language
How do you do the following?
What You Should Already Know
Presentation transcript:

Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2

Problem n Write a program to read six integers... n...& print them out in reverse order n For example: n Can’t use a single-variable loop  need to remember all 6 numbers Enter the six numbers below: In reverse order they are: 41, 99, 2, 7, 3, and 5 Reverse6.java

Solution int n1, n2, n3, n4, n5, n6; S.o.p(“Enter the six numbers below:\n”); n1 = kbd.nextInt(); n2 = kbd.nextInt(); n3 = kbd.nextInt(); n4 = kbd.nextInt(); n5 = kbd.nextInt(); n6 = kbd.nextInt(); kbd.nextLine(); S.o.p(“In reverse order they are:\n” + n6 + “, ” + n5 + “, ” + n4 + “, ” + n6 + “, ” + n5 + “, ” + n4 + “, ” + n3 + “, ” + n2 + “, and ” + n1); + n3 + “, ” + n2 + “, and ” + n1);

Related Problem n Write a program to read six HUNDRED integers & print them out in reverse order n Need 600 ints: declare, input, & output n Individually named: int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14, n15, n16, n17, n18, n19, n20, n21, n22, n23, n24, n25, n26, n27, n28, n29, n30, n31, n32, n33, n34, n35, n36, n37, n38, n39, n40, n41, n42, n43, n44, n45, n46, n47, n48, n49, n50, n51, n52, n53, n54, n55, n56, n57, n58, n59, n60, n61, n62, n63, n64, n65, n66, n67, n68, n69, n70, n71, n72, n73, n74, n75, n76, n77, n78, n79, n80, n81, n82, n83, n84, n86, n86, n87, n88, n89, n90, Reverse600HardWay.java

A Better Way: Arrays n int[] n = new int[600]; // creates 600 ints n n is called an array (of ints) n n has 600 components or elements  each one is an int variable n Their names are:  n[0], n[1], n[2], n[3], n[4],..., n[599] n Number in [brackets] is called the index

Multiple Variables vs. Array int n0, n1, n2, n3, n4, n5, n6, n7, n8, n9; int[] n = new int[10]; n0 n3 n1 n2 n4 n5 n6 n7 n8 n9 n n[0] n[3] n[1] n[2] n[4] n[5] n[6] n[7] n[8] n[9]

Thinking of Array Elements n n[0], n[1], n[2],... are just better ways to write n0, n1, n2,... n Why?  because you can say n[i] for the i th n…  …and then you can put it in a loop for (int i = 0; i < 600; i++) { … n[i] … } Remember this! You’ll see it a LOT!

Using Arrays n Reading and printing those 600 ints? n[0] = kbd.nextInt(); n[1] = kbd.nextInt(); n[2] =... System.out.print(n[599] + ‘ ’ + n[598] + ‘ ’ …); n No—use loops for (int i = 0; i < 600; i++) n[i] = kbd.nextInt(); n[i] = kbd.nextInt(); for (int i = 599; i >= 0; i--) System.out.print(n[i] + ‘ ’); System.out.print(n[i] + ‘ ’); Reverse600EasyWay.java

Notes on Array Indices n We declare int[] n = new int[10]; but there is no element called n[10]  elements go from 0 to 9  any other number is out of bounds »crash with ArrayIndexOutOfBoundsException »crash message says what the wrong index was n Low numbers are at front or top of the array n High numbers are at back or bottom ArrayCrash.java

Notes on Array Indices n Index will usually be a simple variable  the loop control variable: for (int i = 0; i < MAX; i++) {... num[i]... } n Index can be any int-valued expression... num[i + 1]...in an i loop... num[i – 1]...in an i loop... num[10*r + c]...in nested r & c loops... num[i + 1]...in an i loop... num[i – 1]...in an i loop... num[10*r + c]...in nested r & c loops See, for example, StudentNames.java

Array Base Types n Arrays can be of any base type, any size int[] score = new int[600]; double[] weight = new double[70]; boolean[] answers = new boolean[10]; String[] words = new String[5000]; n …any type at all Scanner[] scanners = new Scanner[2]; Student[] myStudents = new Student[10]; The text recommends singular names. I tend to use plural.

Array Sizes n Remember to declare constants for numbers you use in multiple places  like in array declaration and loop! int[] nums = new int[NUM_ITEMS]; int[] nums = new int[NUM_ITEMS]; for (int i = 0; i < NUM_ITEMS; i++) for (int i = 0; i < NUM_ITEMS; i++) nums[i] = kbd.nextInt(); nums[i] = kbd.nextInt(); n Makes it easy to change the number later // # elements – change to 600 when debugged! public static final int NUM_ITEMS = 6;

Arrays Know Their Own Length n Instance variable length public static final int MAX_WORDS = 200; … String[] word = new String[MAX_WORDS]; String[] word = new String[MAX_WORDS]; if (word.length != MAX_WORDS) { if (word.length != MAX_WORDS) { System.err.println(“Your computer is broken!”); System.err.println(“Your computer is broken!”);} NOTE: it’s not a method; it’s a public instance variable

Creating Arrays with Values n Create an array object by listing elements int[] arr = new int[]{2, 3, 5, 7, 11}; n It knows its own length! for(int i = 0; i < arr.length; i++) { System.out.print(arr[i] + “ ”); } n Can change the array later arr = new int[]{13, 17, 19, 23}; Initialize.java

What Do We Use Arrays For? n Lists, mostly  when we need to remember the earlier values after we’ve read the later ones »otherwise we can just use one variable in a loop n Example:  read a list of numbers, calculate its average, then say how different each number is from the average

Average and Differences // read and sum the numbers int[] num = new int[NUM_ITEMS]; int sum = 0; S.o.p(“Enter the ” + NUM_ITEMS + “ items below”); for (int i = 0; i < NUM_ITEMS; i++) { num[i] = kbd.nextInt();// remember the # num[i] = kbd.nextInt();// remember the # sum += num[i];// add it to sum sum += num[i];// add it to sum} // calculate the average double ave = (double)sum / (double)NUM_ITEMS; // print the difference from the average of each for (int i = 0; i < NUM_ITEMS; i++) { S.o.p((num[i] – ave)); S.o.p((num[i] – ave));} WeeklyTemps.java

Exercise n Declare this array of Strings:  print it out on one line (with spaces between)  DON’T COUNT THE WORDS! word “to” “be” “or” “not” “to” “be”

Java Arrays Created at Run Time n Can ask the user how big to make an array »can’t do that in C++ System.out.print(“How many students? ”); int numStu = kbd.nextInt();kbd.nextLine(); String[] name = new String[numStu]; System.out.println(“What are their names?”); for (int s = 0; s < numStu; s++) { name[s] = kbd.nextLine(); } StudentNames.java

Array Lengths are Final n Can’t change the size of an array after you create it(*) int[] n = new int[10]; System.err.println(“Oops! Need it bigger!”); n.length = 20;// illegal n (*) But you can change the variable to point to a new (larger) array! int[] n = new int[10]; System.err.println(“Oops! Need it bigger!”); n = new int[20];// OK! Bigger.java

But What About… n New, larger array is all zeroes! n If you want to keep the old values, you need to copy them into the new array int[] num = new int[]{1,2,3,4,5}; int[] bigger = new int[2 * num.length]; for (int i = 0; i < num.length; i++) { bigger[i] = num[i]; bigger[i] = num[i];} num = bigger; numbigger BetterBigger.java

Command Line Arguments n Remember how we declare main? public static void main(String[] args)  never really explained String[] args  it’s an array of Strings... ...passed into your program... ...from the “command line” prompt] java PrintArgs command line arguments My 3 command line arguments were: 0: “command” 1: “line” 2: “arguments”

Command Line Arguments n Add words after the name of the class n They get passed to the program »(unless they start with, or...) n Appear in the String[] parameter of main  each word is a separate array element prompt] java PrintArgs command line My 2 command line arguments were: 0: “command” 1: “line”

NetBeans & the Command Line n File > Project Properties…  or right-click on project name in Projects pane

Command Line Arguments n You can use args like any other array  ask it its length  loop thru its elements  ask for some element System.out.println(“My ” + args.length + “ arguments:”); for (int i = 0; i < args.length; i++) { System.out.println(i + “:\t\"” + args[i] + “\"”); } args “command” “line” My 2 arguments: 0: "command" 1: "line"

args is a String[] n OK to have a String[]  can have an array of anything (pretty much) n Even if you type in numbers! »you can use Integer.parseInt(args[i]) to get the integer value of args[i] prompt] java PrintArgs 5 10 My 2 command line arguments were: 0: “5” 1: “10” see AddArgs.java

Arrays as Parameters n args is a String[] parameter for main n Other methods can have [] parameters, too  just declare the parameter to be an array! public static int sumArray(int[] arr) n It’s just like any other parameter  gets its value from the method call n It’s just like any other array  it knows how long it is

Method to Sum an Array n Array comes from caller int[] n = new int[]{2, 3, 5, 7, 11}; int addedUp = sumArray(n); n Method adds up its elements public static int sumArray(int[] arr) { int sum = 0; int sum = 0; for (int i = 0; i < arr.length; i++) { for (int i = 0; i < arr.length; i++) { sum += arr[i]; sum += arr[i]; } return sum; return sum;} ArrayMethod.java

Exercise n Write a method that receives an array of words and prints them out one per line. n Write a method that receives an array of doubles and returns the largest value in it

Returning Arrays n Methods can return arrays  return type is an array type public int[] dice(int howMany) { … } public String[] wordsFrom(String line) { … } n The array to be returned is (usually) new int[] result = new int[howMany]; for (int d = 0; d < howMany; ++d) { result[i] = 1 + (int)(6 * Math.random()); result[i] = 1 + (int)(6 * Math.random());} return result; ArrayReturn.java

Exercise n Make a method that returns a specified number of copies of a word in an array  for example: String[] items = copies(6, "Hello"); items “hello”

Printing an Array n Can’t just use System.out.print: int[] a = new int[]{1,2,3,4}; System.out.println(a);  they don’t have a toString method of their own  we can’t add one to them n Could write a method  but we’d need lots of them…  …and that’s such a pain.

The Arrays Class n java.util.Arrays has helper methods:  toString method for arrays int[] a = new int[]{1,2,3,4}; System.out.println(Arrays.toString(a));  works for any kind of array!  needs to be imported n java.util.Arrays also includes methods to copy, search, fill, compare and sort arrays! [1, 2, 3, 4] [1.0, 2.2] [word1, word2]

Sorting an Array n Just give the array to Arrays.sort n It’ll come back sorted int[] a = new int[]{4, 2, 7, 1, 9, 9, 4}; Arrays.sort(a);System.out.println(Arrays.toString(a)); n Works for (almost) any kind of array  works for Strings – sort of »it’s not quite what you’d expect [1, 2, 4, 4, 7, 9, 9] ArraySorter.java

Modifying Arrays n Arrays can be modified by methods int[] a = new int[] {1, 2, 3, 4}; doubleEachElement(a);System.out.println(Arrays.toString(a)); n Just a normal method public static void doubleEachElement(int[] arr) { for (int i = 0; i < arr.length; ++i) { arr[i] *= 2; } } [2, 4, 6, 8] ArrayDoubler.java

Reference Types n Variables in Java are references »except primitive types like int, double, boolean, …  they point to objects int[] a = new int[]{1, 2, 3, 4}; Student s = new Student(“Jo”); String word = “Hi!”; & a & s & word “Hi!” A “Jo” 0

Co-Reference n Two variables can refer to the same object Car myCar = new Car(blue);// new Car Car stevesCar = new Car(blue);// new Car, same colour Car disCar = myCar;// same Car as myCar disCar.setColor(green);// myCar is now green & myCar: & disCar: & stevesCar: Car variablesCar objects disCar and myCar are not two different cars. They’re two different names for the same car.

Array (and Object) Parameters n Method call passes reference to object  parameter points to same object as argument  thus method can change the object int[] a = new int[] {1, 2, 3, 4}; doubleEachElement(a);… public static void doubleEachElement(int[] arr) { for (int i = 0; i < arr.length; ++i) { arr[i] *= 2; } } & a & arr ArrayDoubler.java

Doesn’t Work for Primitives n Method call passes actual value  parameter has same value as argument  thus method cannot change argument variable int a = 3; doubleValue(a);… public static void doubleValue(int n) { n *= 2; } a 3 3 n 6 ArrayDoubler.java

Can’t Change Argument Variable n Method call passes reference to object  parameter points to same object as argument  but it’s NOT the same variable! int[] a = new int[] {1, 2, 3, 4}; changeTheArray(a);… public static void changeTheArray(int[] arr) { arr = int[] {5, 6, 7, 8}; } & a & arr ArrayDoubler.java

Variable vs. Object n Usually think of them as the same thing  but they’re not actually the same thing n Variable is used to refer to an object  essentially a name we use for the object n The object is a separate thing  it has the data in it  it’s the one you talk to when you use the dot (.) »but before the dot is the name we use for the object

Null References n A reference variable can refer to nothing int[] a = null; Student s = null; String word = null;  it’s not pointing at any object  can make it point to an object later a = new int[]{3, 4, 5}; / a / s / word & a

Null Pointer Exception n Can’t talk to things that don’t exist »Java won’t let you  can’t use. with a null variable »can’t use […] either »program will crash int[] a = null; for (int i = 0; i < a.length; ++i) { a[i] = (i + 1); a[i] = (i + 1);} / a Exception in thread "main" java.lang.NullPointerException

Array Exceptions You Might See n ArrayIndexOutOfBoundsException  you tried to get an array element …  … but that element doesn’t exist n NullPointerException  you tried to get an array element …  … but that array doesn’t exist n When your program crashes, read the message and try to understand it!

Questions