Welcome to Lesson 21!


Learning Objectives
By the end of today's class, you should know...
  • How do you pass an array to a method as a parameter?
  • How do you return an array from a method?

Announcements

  • Last Lab due Friday at midnight
    • Final Exam on Monday at 9:15am in this classroom
      • One method from each of the Methodical assignments
      • Draw heavily from practice quiz 8 (today in class)
      • One program from your final assignment
    • Last homework due Friday at midnight
      • Will select one of these two programs to put on your final exam
    • Last in-person office hour on Thursday from 2:30-3:20pm
      • No late work accepted after this office hour - no exceptions!
      • No late work more than one week old
      • Get there early as it will be packed!


    Review Activity

    1. Given the following lines of code, write a loop to read in the file word by word:

    String word;

    int count = 0;

          File file = new File("in.txt");

    Scanner input = new Scanner(file);

    while(  ????                      ) {    

        word = ????;

        count++;

        System.out.println("Word " + count + ": " + word);

    }

    2. Given the following lines of code, write a loop to read in the file line by line:


    String line;

    int count = 0;

          File file = new File("in.txt");

    Scanner input = new Scanner(file);

    while(  ????                      ) {    

        line = ????;

        count++;

        System.out.println("Line " + count + ": " + line);

    }


    3. Declare an array of Strings called pets and assign it the values dog, cat, rabbit, bird in TWO DIFFERENT WAYS (static and non-static initialization)


    4. Print out the contents of the above array using a for loop.


    Arrays Continued

    Arrays and Methods

    • When writing a method with an array parameter, we place an empty [] after the datatype or parameter name:
      public static void print(int values[]); //will work for an array of any size
      
    • When we call the method, we do NOT include the []:
      print(data); // name of the array is data
      
    • Instead, we pass in the name of the array.

    Example program passing an array to a method

    public static void print(int values[]){
            for (int i = 0; i < values.length; i++)
                System.out.println(values[i]);
        }

        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int[] scores = {90, 89, 76, 55, 91};
            print(scores);
         
        }

    • Unlike other parameters, you can pass the array into the method and then alter the array inside of the method without needing to return a new array.
    • For example, what do you think will be the result of running the following program?
    import java.util.Scanner;
    public class Arrays {
       
        public static void assignValues(int values[]){
            for (int i = 0; i < values.length; i++){
                values[i] = i;
            }
        }

        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int[]  arr = new int[10];
            assignValues(arr);
         
            for (int i = 0; i < arr.length; i++){
                System.out.println(arr[i]);
            }
        }
           

    • It is also possible to return an array from a method.
    • For example:



    /**
     *
     * @author Jennifer Parrish
     */
    import java.util.Scanner;
    public class Arrays {
       
        public static int[] assignValues(int values[]){
            for (int i = 0; i < values.length; i++){
                values[i] = i;
            }
            return values;
        }



        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int[]  arr = new int[10];
            arr = assignValues(arr);

            System.out.println("After filling the array:");
            for (int i = 0; i < arr.length; i++){
                System.out.println(arr[i]);
            }

           
        }
     
    }



    Activity 21.1: Exploring Arrays (10 pts)
    • In this exercise we explore declaring, allocating and assigning values to arrays containing lists of data
    • Create a Java project called Arr
    • Add the following method to the code:
      public static void print(int values[]) {
          for (int i = 0; i < values.length; i++) {
              System.out.print(values[i] + " ");
          }
      }
      
    • Compile your code to make sure it has correct syntax.

      If you have problems, ask a classmate or the instructor for help as needed.

    • Declare and initialize an array for a list of 10 integer scores:
      int scores[] = {90, 91, 92, 93, 94, 95, 96, 97, 98, 99};
      
    • After declaring and initializing the array, call the print() method using the code:
      System.out.println("Integer exam scores:");
      print(scores);
    • Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like this:
      Integer exam scores:
      90 91 92 93 94 95 96 97 98 99
      
    • Declare and initialize an array of double values holding rainfall values (in inches) 23.4, 16.4, 18.9, and 52.7
    • Write another print() method with one parameter for the array of double values.
    • After declaring and initializing the array, call the print() method.
    • Note that you can re-use the name print for this second method. The compiler will know they are different methods because the parameters are different. This is called method overloading.
    • Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like this:
      Integer exam scores:
      90 91 92 93 94 95 96 97 98 99
      Double rainfall in inches:
      23.4 16.4 18.9 52.7
      
    • Declare and allocate an array of char values and assign it the vowels a, e, i, o and u.
    • After declaring and initializing the array, write another print method to display it. Again, this method should be named print(). Then, call this method in main.
    • Compile and run the program to make sure you made the changes correctly. When you run the program, the output should look like this:
      Integer exam scores:
      90 91 92 93 94 95 96 97 98 99
      Double rainfall in inches:
      23.4 16.4 18.9 52.7
      Char vowels:
      a e i o u 
    • Finally write a method called addExtraCredit with the following signature:

    public static int[] addExtraCredit(int[] scores){

        //fill in method body here

    }

    • This method should add 5 points of extra credit to each value in the scores array. It will return the new array with the extra credit added.
      • Hint: Add 5 to each array element using a for loop to iterate through all values in the scores array.
    • Write the method and then call it on the scores array like so:

    scores = addExtraCredit(scores);

    • Now print out the scores array by calling the print method to verify that the extra credit got added correctly.
    • Your output should now look like the following:
    Integer exam scores:
    90 91 92 93 94 95 96 97 98 99
    Double rainfall in inches:
    23.4 16.4 18.9 52.7
    Char vowels:
    a e i o u
    Exams scores with extra credit
    95 96 97 98 99 100 101 102 103 104

    • Submit your program to Canvas when you are finished.


    Activity 21.2: Arrays and Methods Worksheet (10 pts)

    • Copy the following into a new file called ArrayMethods.java.
    • Write the methods one-by-one and then compile and run your code to make sure they are working properly.
    • When your code passes all of the tests, upload your file to Canvas.
      public class ArrayMethods {

          /**
           * prints the contents of an array to the console using a for loop
           * @param data the array to print
           */
          public static void printArray(int[] data) {
              return;
          }

          
          /**
          * Given an array of ints, return true if 10 appears as
          * either the first or last element in the array. The array will be size 1 or more.
          * first10Last([1, 2, 10]) → true
          * first10Last([10, 1, 2, 3]) → true
          * first10Last([13, 10, 1, 2, 3]) → false
          * @param data the array of integer values
          * @return whether or not 10 appears as the first or last element
          */
          public static boolean first10Last(int data[]) {
              return false;
          }
          
          /**
          * Given an array of ints, return true if the array is size 1 or more,
          * AND the first element and the last element are equal.
          * equalFirstLast([1, 2, 3]) → false
          * equalFirstLast([1, 2, 3, 1]) → true
          * equalFirstLast([1, 2, 1]) → true
          * @param array the array of integers
          * @return whether the first and last element are identical
          */
          public static boolean equalFirstLast(int[] array){
              return false;
          }
          
          /**
          * Given an array of ints, add 2 to each element in the array
          * return nothing.
          * arrayPlus2([1,2,3]) -> [3, 4, 5]
          * arrayPlus2([10, 30, 50, 79, 85]) -> [12, 32, 52, 81, 87]
          * arrayPlus2([5]) -> [7]
          * @param array the array of integer values
          */
          public static void arrayPlus2(int array[]) {
              return;
          }
          
          /**
           * Given an array of ints, multiplies each element in the array by itself
           * squareArray([1,2,3]) -> [1, 4, 9]
           * squareArray([3, 5, 6, 8, 9]) -> [9, 25, 36, 64, 81]
           * squareArray([5]) -> [25]
           * @param array the array of integer values
           */
          public static void squareArray(int[] array){
              return;
          }
          

          public static void main(String[] args)
          {
            
              boolean answer;
            
              System.out.println("***Testing first10Last***\n");
              int array1[] = {1, 2, 10};
              answer = first10Last(array1);
              System.out.println("Should print true: " + answer);
              int array2[] = {10, 1, 2, 3};
              answer = first10Last(array2);
              System.out.println("Should print true: " + answer);
              int array3[] = {13, 10, 1, 2, 3};
              answer = first10Last(array3);
              System.out.println("Should print false: " + answer);
              System.out.println();

              System.out.println("***Testing equalFirstLast***\n");
              int array4[] = {1, 2, 3};
              answer = equalFirstLast(array4);
              System.out.println("Should print false: " + answer);
              int array5[] = {10, 20, 50, 60, 80, 90, 10};
              answer = equalFirstLast(array5);
              System.out.println("Should print true: " + answer);
              int array6[] = {1};
              answer = equalFirstLast(array6);
              System.out.println("Should print true: " + answer);
              System.out.println();

              System.out.println("***Testing arrayPlus2***\n");
              int array7[] = {1, 2, 3};
              arrayPlus2(array7);
              System.out.println("Should print 3 4 5: ");
              printArray(array7);
              System.out.println();
              int array8[] = {10, 30, 50, 79, 85};
              arrayPlus2(array8);
              System.out.println("Should print 12 32 52 81 87: ");
              printArray(array8);
              System.out.println();
              int array9[] = {5};
              arrayPlus2(array9);
              System.out.println("Should print 7: ");
              printArray(array9);
              System.out.println("\n");

              System.out.println("***squareArray***\n");
              int array10[] = {1, 2, 3};
              squareArray(array10);
              System.out.println("Should print 1 4 9: ");
              printArray(array10);
              System.out.println();
              int array11[] = {3, 5, 6, 8, 9};
              squareArray(array11);
              System.out.println("Should print 9 25 36 64 81: ");
              printArray(array11);
              System.out.println();
              int array12[] = {5};
              squareArray(array12);
              System.out.println("Should print 25: ");
              printArray(array12);
              System.out.println("\n");

              System.out.println("***End of Tests***");
             


          }

      }

    Activity 21.3: Practice Quiz 8 (10 pts)
    • With a partner, copy and paste the practice quiz into a new MS Word document or Google doc.
    • Complete the practice quiz, which has questions that are very similar to those on the final
    • Upload the completed quiz when you are finished.

    Answer Key


    Wrap Up
    • With your partner, answer the questions from today's learning objectives


    Upcoming Assignments

    ~ Good Luck Studying! ~