Welcome to Lesson 21!


Learning Objectives
By the end of today's class, you should know...
  • How do you use arrays as method parameters?
  • How do you return an array from a method?
  • How do you use loops to read from and write to a file in your program?

Announcements

  • Last Lab due Friday at midnight
    • Final Exam one week from today -  Tuesday, June 26 at 1:45pm in this classroom
      • Will post practice exam on Thursday
      • No makeup finals, no exceptions!
    • Last in-person office hour this Thursday from 12:30-1:20pm
      • No late work accepted after this office hour - no exceptions!
      • In other words, Assignment 21 must be submitted on time and correctly!
      • No late work more than one week old
      • Get there early as it will be packed!
        • Only 6-8 people can be helped in that time frame
        • Try to come to a different office hours if you can
    • Last homework assigned for tonight!
    • Quiz 7 answer key posted under tonight's assignment
    • Project Presentations next class


    Review Activity

    With a partner, answer the following questions:

    • Assume you have a text file named infile.txt that contains the following data: 13.5 19.0 12.4
    • Write four lines of code to do the following:
      1. Create a new File object to connect to infile.txt
      2. Create a new Scanner object to read from the file
      3. Read the first number from the file and store it as a double variable named num1.
      4. Close the Scanner.
    • Assume you have a text file named outfile.txt
    • Write four lines of code to do the following:
    1. Create a new File object to connect to outfile.txt
    2. Create a new PrintWriter object to write to the file
    3. Write the message "Hello World!" to the file
    4. Close the PrintWriter.
    • 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)
    • Print out the contents of the above array using a for loop.


    File I/O Continued

    Using Loops to Read Files

    • Sometimes you do not know how many lines are in a file
    • To solve this, the typical approach is to use a loop to process the file
    • The Scanner object has methods like hasNext() to see if there is any more input in the stream
    • You can use these methods to signal when your program reaches the end of a file

    Example Program Testing for End-of-File

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import java.io.*;
    import java.util.Scanner;

    public class Files {
    public static void main(String[] args)
    throws IOException {
    File data = new File("sonnet.txt");
    Scanner input = new Scanner(data);

    while (input.hasNextLine()) {
    String line = input.nextLine();
    System.out.println(line);
    }
    input.close();
    }

    }

    Some Test Methods of a Scanner Object

    Method Description
    hasNext() Returns true if this scanner has another token in its input.
    hasNextLine() Returns true if there is another line in the input of this scanner.
    hasNextDouble() Returns true if the next token can be interpreted as a double value.
    hasNextInt() Returns true if the next token can be interpreted as an int value.
    
    

    Activity 21.1: Averages (10pts)

    • We are going to write a program that takes in a list of numbers of unknown size from a file, and then outputs the average of these numbers.
    • This activity will help you practice using a loop to help you read data from a file.
    • Open up a new Java project and name it Averages
    • Now add the two import statements that are required for file I/O to the top of your program:
    import java.util.Scanner;
    import java.io.*;

    • Next, lets create a new File variable at the top of main and pass it in the name of the file "nums.txt"
    File infile = new File("nums.txt");
    • Then, let's Scanner to open this file.
    Scanner input = new Scanner(infile);

    • Next, lets read in the numbers from the file. Since we are computing the average of the numbers, we need two pieces of information
    1. The sum of the numbers
    2. How many numbers there are
    • Remember: Average = sum / count
    • Therefore, as we read in the numbers from the file, we need to computer their sum and count how many there are.
    • We will therefore need two variables to keep track of this information. Add the following two variable declarations to the top of main:
    double sum = 0.0;
    int count = 0;
    • We will also need a variable to temporarily store each number as we read it in from the file. Add an additional variable declaration to the top of main like so:
    double num;
    • Now, let's read in the numbers from the file and process them inside a loop. Add the following loop to your program:
    while (input.hasNextInt()) {
        num = input.nextInt();
        System.out.println("Processing the number: " + num);
        sum += num; //adding the number to our running total for the sum
        count++; //counting how many numbers are in the file
    }
    • Now, let's print the average to the console and output it to a file.
    • To print the average to the console, add the following line of code:
    System.out.println("The average is: " + sum/count);
    • To output the average to a file, we need to open a new output file. Below the print statement, add the following line of code:
    File outfile = new File("average.txt");
    • Then, we need to connect this file to an output stream.
    PrintWriter output = new PrintWriter(outfile);
    • Finally, lets write the average to the file.
    output.println("The average is: " + sum/count);
    • As a last step we need to close our input and output streams. Add the following lines of code to the bottom of main:
    input.close();
    output.close();
    • Let's create a file to test our program. Open up a new empty file in Eclipse and name file nums.txt. In the file, add a list of numbers like this:
    10 20 30 40 50
    • Now, run the code and open up your file to make sure everything is working properly. Open up the file averages.txt and verify that you got the correct output.
    • When you are finished, upload Averages.java to Canvas.

    Activity 21.2: Sonnet Statistics (10 pts)

    • Open up a new Java project named Statistics and add the starter code below to it:
    import java.io.*;
    import java.util.Scanner;

    public class Statistics {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws IOException{

            int count = 0;

            String word, line;

            //rest of code goes here

        }

    }

    • Now, using Eclipse, create a new empty file called sonnet.txt and copy and paste the below sonnet into your file:

    Shall I compare thee to a summer’s day?
    Thou art more lovely and more temperate:
    Rough winds do shake the darling buds of May,
    And summer’s lease hath all too short a date;
    Sometime too hot the eye of heaven shines,
    And often is his gold complexion dimm'd;
    And every fair from fair sometime declines,
    By chance or nature’s changing course untrimm'd;
    But thy eternal summer shall not fade,
    Nor lose possession of that fair thou ow’st;
    Nor shall death brag thou wander’st in his shade,
    When in eternal lines to time thou grow’st:
    So long as men can breathe or eyes can see,
    So long lives this, and this gives life to thee.

    • We are going to write some code to count the number of words and the number of lines in this file.
    • Declare two new files at the top of your program:

    File infile = new File("sonnet.txt");

    File outfile = new File("statistics.txt");


    • Also declare a new Scanner and connect it to infile.
    • Now, let's write a while loop to count up how many words are in the file.
    while (input.hasNext()) {
        word = input.next();
        count++;
    }
    • Finally, declare a new PrintWriter, connect it to outfile and print out the number of words contained in the file
        output.println("The sonnet has " + count + " words");
    • Now, close your input file stream.
        input.close();

    • Now, we need to count the number of lines in the file.
    • For this purpose, we are going to need a new input file stream as we already used the previous one to count the number of words in the file (and we cannot reset the input stream to point to the beginning of the file).
    • Add the following code to your program below the statement to close fin:
        input = new Scanner(infile);

    • Next, we are going to write a while loop to count the number of lines in the file.
    count = 0; //reset count variable to 0
    while (?????) {
        //what goes here?
        count++;
    }
    • Write an print statement to print out the number of lines in the sonnet.
    The sonnet has 14 lines.
    • Finally, close input and output and run your program.
    • Note that you should get 114 words and 14 lines.
    • Did you get the expected result inside of statistics.txt?
    • Submit your code to Canvas when you are finished.


    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.3: 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
      
    • Next, write a method, named addExtraCredit. This method uses a for loop to add 5 points to each exam score in the scores array.
    • The method should have the following signature:      

    public static void addExtraCredit(int values[]) {
        //Write the body of the method here
    }

    • Next, call this method, passing in the scores array.
    • Then, call the print method again to display the values, along with the message After adding extra credit:
    • Note: Do NOT print inside of the addExtraCredit method. Call the print method to print the array. AddExtraCredit should only add extra credit to the scores. It should not print anything inside the body of the method.

    • Compile and run the program to make sure you made the changes correctly. When you run the program, the new output should look like this:
      After adding extra credit:
      95 96 97 98 99 100 101 102 103 104
      
    • 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
    After adding extra credit:
    95 96 97 98 99 100 101 102 103 104
    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
      After adding extra credit:
      95 96 97 98 99 100 101 102 103 104
      Double rainfall in inches
      23.4 16.4 18.9 52.7
      Char vowels
      a e i o u
      

    • When your program gives the above output, upload your program to Canvas.

    Upcoming Assignments:

    ~See You Thursday!~