Welcome to Lesson 20!


Learning Objectives
By the end of today's class, you should know...
  • How do you use loops to process data in a file?
  • What is an array?
  • How do you declare an array and assign it values?
  • How do you use arrays as the parameters to methods?

Announcements

  • Quiz After the Break
    • Methods
  • Final Lab due Friday

Review Activity

  • Write 4 lines of code as follows:
    • Declare a new File to open "output.txt" for writing
    • Declare a new PrintWriter to write out to that file
    • Write out the word "Hello" to the file.
    • Close the file


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 in = new Scanner(data);

while (in.hasNext()) {
String line = in.nextLine();
System.out.println(line);
}
in.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 20.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 Netbeans 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 Catalyst.










Activity 20.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 Netbeans, 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.

  • If copy and paste is not working, try adding these lines, running the code and then removing them:

File data = new File("sonnet.txt");
        //Scanner in = new Scanner(data);
        int count = 0;
        PrintWriter out = new PrintWriter(data);
        out.print("Shall I compare thee to a summer’s day?\n" +
"Thou art more lovely and more temperate:\n" +
"Rough winds do shake the darling buds of May,\n" +
"And summer’s lease hath all too short a date;\n" +
"Sometime too hot the eye of heaven shines,\n" +
"And often is his gold complexion dimm'd;\n" +
"And every fair from fair sometime declines,\n" +
"By chance or nature’s changing course untrimm'd;\n" +
"But thy eternal summer shall not fade,\n" +
"Nor lose possession of that fair thou ow’st;\n" +
"Nor shall death brag thou wander’st in his shade,\n" +
"When in eternal lines to time thou grow’st:\n" +
"So long as men can breathe or eyes can see,\n" +
"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 your last statement:
    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 Catalyst when you are finished.

Arrays

Defining Arrays

  • An array is a collection of data items all of the same type
  • You declare an array like this:
    dataType[] variableName = new dataType[size];
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • size: the number of data items the array can hold
  • For example, the following is the declaration of an array named scores that holds 10 values of type int:
    int[] scores = new int[10];
  • We can have arrays of any type:
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;
  • Arrays like this can never change size and the array size must be set when the program is compiled
  • When defining an array, you must guess the maximum number of elements you need to store:
    int[] scores = new int[100];
    
  • The programmer must keep track of the capacity
  • We use a final to hold the capacity of the array as shown below:

final int CAPACITY = 10;

int[] scores = new int[CAPACITY];

  • This allows us to alter the size anywhere in our code
  • If we need to change the size, we change only a single constant and recompile
  • When a program executes this statement, it creates 10 contiguous slots in memory like this:
    scores = 
     
     
     
     
     
     
     
     
     
     
  • Each of the memory slots can hold one data value

Initializing Array Items

  • We specify which slot of an array to access with the [] operator:
    scores[4] = 98;
  • The indexes of arrays are numbered starting at 0
  • We can assign a value to an array element any time after it is declared:
    final int MAX_SCORES = 5;
    int[] scores = new int[MAX_SCORES];
    scores[0] = 90;
    scores[1] = 95;
    scores[2] = 87;
    scores[3] = 89;
    scores[4] = 98;
    
  • We can also initialize array elements in the declaration statement:
    • Called static initialization
    • We use a comma-separated list inside curly-braces
  • For example:
    int[] scores = { 90, 95, 87, 89, 98 };
    
  • This produces the same array as in the previous example
  • The compiler computes the size automatically by counting the items in the list
  • If we want a larger array with only the first few elements initialized, we can use:
    int scores[MAX_SCORES] = {90, 95, 87};
    
  • Note that if we do not assign a value to an array element, it will still contain a default value.
Default Array Values
  • When an array is declared, Java automatically assigns each element a default value: false for booleans, 0 for numerical types

Accessing Array Items

  • To access the slots in an array, we must specify which slot to use with the [] operator
  • For instance:
    scores[4] = 98;
  • The number inside the brackets is called an index or subscript
  • In Java, the slots of an array are numbered starting at 0, as shown below:
    scores = 
     
     
     
     
    98
     
     
     
     
     
    [0]
    [1]
    [2]
    [3]
    [4]
    [5]
    [6]
    [7]
    [8]
    [9]
  • Thus, assignment to the slot with an index of 4 is put into the fifth slot

Using Slots

  • We declared our example array with a data type of int:
    int[] scores = new int[10];
  • Because scores is an array containing int values, we can use a slot, such as scores[4], just like any variable of type int:
    scores[4]++;
    System.out.println(scores[4]);
    
  • This includes using a slot as an argument to a method with a parameter of the same type:
    void myFun(int singleScore){//method body}
    ...
    myFun(scores[4]); 

Array Length

  • We can always access the length of an array using .length

System.out.println(scores.length);

  • Note that the length of the array is always one less than its last index

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

Image source.

Using Arrays to Collect Data Items

  • Note that the index of an array can be any integer value
  • Thus, we can use an integer variable for the index
  • We can use an integer variable with a loop to read data into the array
  • Also, we can display the contents of an array using a loop
  • The following program shows an example of collecting and displaying data items


Example Program Using Arrays to Collect and Display Data Items

package arrays;

/**
*
* @author parrishj
*/
import java.util.Scanner;
public class Arrays {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int[] scores = new int[5];
System.out.println("Array elements initialized to 0:");
for (int i =0; i <scores.length; i++){
System.out.println("Index " + i + ": " + scores[i]);
}
System.out.println("\nEnter " + scores.length + " scores:");
for (int i =0; i <scores.length; i++){
scores[i] = input.nextInt();
}
System.out.println("\nYou entered:");
for (int i =0; i <scores.length; i++){
System.out.println("Score " + i + ": " + scores[i]);
}
}

}

Arrays

Defining Arrays

  • An array is a collection of data items all of the same type
  • You declare an array like this:
    dataType[] variableName = new dataType[size];
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • size: the number of data items the array can hold
  • For example, the following is the declaration of an array named scores that holds 10 values of type int:
    int[] scores = new int[10];
  • We can have arrays of any type:
double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings;
  • Arrays like this can never change size and the array size must be set when the program is compiled
  • When defining an array, you must guess the maximum number of elements you need to store:
    int[] scores = new int[100];
    
  • The programmer must keep track of the capacity
  • We use a final to hold the capacity of the array as shown below:

final int CAPACITY = 10;

int[] scores = new int[CAPACITY];

  • This allows us to alter the size anywhere in our code
  • If we need to change the size, we change only a single constant and recompile
  • When a program executes this statement, it creates 10 contiguous slots in memory like this:
    scores = 
     
     
     
     
     
     
     
     
     
     
  • Each of the memory slots can hold one data value

Initializing Array Items

  • We specify which slot of an array to access with the [] operator:
    scores[4] = 98;
  • The indexes of arrays are numbered starting at 0
  • We can assign a value to an array element any time after it is declared:
    final int MAX_SCORES = 5;
    int[] scores = new int[MAX_SCORES];
    scores[0] = 90;
    scores[1] = 95;
    scores[2] = 87;
    scores[3] = 89;
    scores[4] = 98;
    
  • We can also initialize array elements in the declaration statement:
    • Called static initialization
    • We use a comma-separated list inside curly-braces
  • For example:
    int[] scores = { 90, 95, 87, 89, 98 };
    
  • This produces the same array as in the previous example
  • The compiler computes the size automatically by counting the items in the list
Default Array Values
  • When an array is declared, Java automatically assigns each element a default value: false for booleans, 0 for numerical types

Accessing Array Items

  • To access the slots in an array, we must specify which slot to use with the [] operator
  • For instance:
    scores[4] = 98;
  • The number inside the brackets is called an index or subscript
  • In Java, the slots of an array are numbered starting at 0, as shown below:
    scores = 
     
     
     
     
    98
     
     
     
     
     
    [0]
    [1]
    [2]
    [3]
    [4]
    [5]
    [6]
    [7]
    [8]
    [9]
  • Thus, assignment to the slot with an index of 4 is put into the fifth slot

Using Slots

  • We declared our example array with a data type of int:
    int[] scores = new int[10];
  • Because scores is an array containing int values, we can use a slot, such as scores[4], just like any variable of type int:
    scores[4]++;
    System.out.println(scores[4]);
    
  • This includes using a slot as an argument to a method with a parameter of the same type:
    public static void myMethod(int singleScore){//method body}
    ...
    myMethod(scores[4]); 

Array Length

  • We can always access the length of an array using .length

System.out.println(scores.length);

  • Note that the length of the array is always one less than its last index

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

Image source.

Using Arrays to Collect Data Items

  • Note that the index of an array can be any integer value
  • Thus, we can use an integer variable for the index
  • We can use an integer variable with a loop to read data into the array
  • Also, we can display the contents of an array using a loop
  • The following program shows an example of collecting and displaying data items


Example Program Using Arrays to Collect and Display Data Items

package arrays;

/**
*
* @author parrishj
*/
import java.util.Scanner;
public class Arrays {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);

int[] scores = new int[5];
System.out.println("Array elements initialized to 0:");
for (int i =0; i <scores.length; i++){
System.out.println("Index " + i + ": " + scores[i]);
}
System.out.println("\nEnter " + scores.length + " scores:");
for (int i =0; i <scores.length; i++){
scores[i] = input.nextInt();
}
System.out.println("\nYou entered:");
for (int i =0; i <scores.length; i++){
System.out.println("Score " + i + ": " + scores[i]);
}
}

}

Wrap Up

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

Upcoming Assignments
  • Assignment 20 due Thursday at 9:00am on Catalyst
  • Final Lab due Friday