Watch the Lesson Video HERE


Welcome to Lesson 21!


Learning Objectives
By the end of today's class, you should know...
  • How can you read in the contents of a file using a loop?
  • How do use a loop to read in the contents of a file of unknown size?
  • Which Scanner methods are useful for reading in the contents of a file of unknown size?
  • More practice with arrays and methods

Announcements

  • Final Exam: March 24 at 11:30am on Canvas
    • No makeups - the exam must be taken on the that day and at that time
    • Exam will have a similar format to your quizzes - short answer, multiple choice, true/false
    • It will appear on Canvas under the module for Week 12
    • I will proctor the exam via Zoom and Canvas
    • You must be online to take the exam at 11:30am, or you might not be allowed to take the exam
      • Exam will be short - except somewhere in the neighborhood of 20 -25 minutes long
    • You will have only one attempt to complete the exam
    • Exam is closed notes, closed technology.
    • Canvas will let me know if you look at any other page besides the exam - in which case you will receive a 0
    • You cannot work with anyone else during the exam - if I see you talking to someone else, then you will receive a 0
    • Tonight's homework will be to download Zoom
    • One of your activities for Thursday, will be to join a Zoom meeting with me to make sure you have installed Zoom properly on your computer.
  • Lab 10 due Friday at midnight
  • No quiz for Friday
  • Last homework of the quarter assigned for tonight!
  • Last office hour of the quarter is this Thursday from 5:00-5:25pm
    • No late work accepted after this office hour
    • No makeup work accepted that is more than one week late
    • I will still answer emails and messages on Canvas, even though I will not hold office hours


Lesson 20 Practice Exam 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 an empty 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.












  • Write the below methods:

  /**
    * Given an array of Strings, print the array
    * to the console, with each element in the array
    * separated by a blank space
    * the method should be named printArray
    * @param data the array of String values
    */
 
 







  /**
    * 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
    */
 


 





/**
    * 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
    */









Wrapping Up File I/O

Using Loops to Read Files

  • Sometimes you do not know how many lines are in a file
  • Sometimes you might want to write a program that reads in files of different lengths
  • 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) - due Thursday, March 19 at 11:20am

  • 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.hasNextDouble()) {
    num = input.nextDouble();
    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) due Thursday, March 19 at 11:20am

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


Activity 21.3: Methods + Arrays Worksheet (10 pts) - due Thursday, March 19 at 11:20am

  • Open a new Java file called ArrayMethods.java.
  • Read the Javadoc comment for each method below and write the method according to the description in the comment
  • Once you are getting the correct output for all tests inside of main, upload MethodicalArrays.java to Canvas
public class ArrayMethods {

    /**
     * Displays the contents of an array on the console
     * with each element separated by a blank space
     * Prints a new line character last
     * @param nums the array to print to the console
     */
    public static void printArray(int[] nums) {
        return;
    }

    
    /**
    * Assuming an array of integers, return true if 1
    * is the first element or 1 is the last element
    * Note: you may assume that you will be given an array
    * of at least length 1
    * is1FirstLast([1, 2, 10]) → true
    * is1FirstLast([10, 1, 2, 1]) → true
    * is1FirstLast([13, 10, 1, 2, 3]) → false
    * @param numbers the array of int numbers
    * @return whether or not 10 is the first or last element
    */
    public static boolean is1FirstLast(int numbers[]) {
        return false;
    }
   
    /**
    * Given an array of int numbers, return true
    * if the array is size 1 or more,
    * AND the first element and the last element are the same.
    * sameFirstLast([1, 2, 3]) → false
    * sameFirstLast([1, 2, 3, 1]) → true
    * sameFirstLast([1, 2, 1]) → true
    * @param numbers the array of integers
    * @return whether the first and last element are the same
    */
    public static boolean sameFirstLast(int[] numbers){
        return false;
    }
   
    /**
    * Given an array of int numbers, add 10 to each element in the array
    * return nothing.
    * arrayAdd10([1,2,3]) -> [11, 12, 13]
    * arrayAdd10([10, 30, 50, 79, 85]) -> [20, 40, 60, 89, 95]
    * arrayAdd10([5]) -> [15]
    * @param array the array of integer values
    */
    public static void arrayAdd10(int array[]) {
        return;
    }
   
    /**
     * Given an array of ints numbers, multiply each element in the array by itself
     * arraySquared([1,2,3]) -> [1, 4, 9]
     * arraySquared([9, 10, 11, 12]) -> [81, 100, 121, 144]
     * arraySquared([151]) -> [22801]
     * @param array the array of integer values
     */
    public static void arraySquared(int[] array){
        return;
    }
   

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

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

        System.out.println("***Testing arrayAdd10***\n");
        int array7[] = {1, 2, 3};
        arrayAdd10(array7);
        System.out.println("Should print 11 12 13: ");
        printArray(array7);
        System.out.println();
        int array8[] = {10, 30, 50, 79, 85};
        arrayAdd10(array8);
        System.out.println("Should print 20 40 60 89 95: ");
        printArray(array8);
        System.out.println();
        int array9[] = {5};
        arrayAdd10(array9);
        System.out.println("Should print 15: ");
        printArray(array9);
        System.out.println("\n");

        System.out.println("***arraySquared***\n");
        int array10[] = {1, 2, 3};
        arraySquared(array10);
        System.out.println("Should print 1 4 9: ");
        printArray(array10);
        System.out.println();
        int array11[] = {9, 10, 11, 12};
        arraySquared(array11);
        System.out.println("Should print 81 100 121 144: ");
        printArray(array11);
        System.out.println();
        int array12[] = {151};
        arraySquared(array12);
        System.out.println("Should print 22801: ");
        printArray(array12);
        System.out.println("\n");

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


    }

}

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


Upcoming Assignments

  • Activities 21.1-21.3 due Thursday at 11:20am
  • Assignment 21 due Thursday at 11:20am
  • Lab 10 due Friday
  • Final Exam on Tuesday, March 24!


~See You Thursday - on Zoom!~