Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2."— Presentation transcript:

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

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: 5 3 7 2 99 41 In reverse order they are: 41, 99, 2, 7, 3, and 5 Reverse6.java

3 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);

4 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

5 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

6 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]

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

8 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

9 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

10 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

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

12 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;

13 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

14 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}; 2 3 5 7 11 Initialize.java

15 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

16 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

17 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”

18 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

19 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

20 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; 123450000000000 12345 numbigger BetterBigger.java

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

22 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”

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

24 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"

25 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

26 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

27 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

28 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

29 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

30 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”

31 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. [I@1db9742

32 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]

33 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

34 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

35 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 1 2 3 4 & s & word “Hi!” A00000001 “Jo” 0

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

37 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 1 2 3 4 & arr 2 4 6 8 ArrayDoubler.java

38 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

39 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 1 2 3 4 & arr 5 6 7 8 ArrayDoubler.java

40 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

41 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 3 4 5 & a

42 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

43 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!

44 Questions


Download ppt "Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2."

Similar presentations


Ads by Google