Welcome to Lesson 20!


Learning Objectives
By the end of today's class, you should know...
  • How do you declare an array?
  • How do you assign it values?
  • What is static initialization?
  • How do you pass in an array to a method or return an array from a method?
  • How do you use loops to process data in files?

Announcements

  • Quizzes on methods overall looked good!
    • If you are struggling with methods, please book a 30 minute free tutoring session on methods with Mega, Gel or Nixon.
  • Lab 10 due Friday
  • Final Exam one week from today
  • Last in-person office hour of the quarter on Thursday at 2:30pm
    • No late work accepted after this office hour
    • No late work more than one week old
  • Final 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.

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[length];
    
  • You can also declare an array like this:
    dataType variableName[] = new dataType[length];
    
  • Where:
    • dataType: the data type of all the array items
    • variableName: the name you make up for the array
    • length: 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];
  • 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
  • We can have arrays of any type:
double[] anArrayOfDoubles;
boolean anArrayOfBooleans[];
char[] anArrayOfChars;
String anArrayOfStrings[];
  • Once you define the length of an array, it cannot change length later in the program.
  • When defining an array, you must guess the maximum number of elements you need to store:
    int[] scores = new int[100];
    
  • If you need to know the length of an array, you can always use the length property (more on this below):
          System.out.println(scores.length) //Will print out 100

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



/**
*
* @author parrishj
*/
import java.util.Scanner;
public class Arrays {
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]);
}
}

}

Activity 20.1: My First Array (10pts)

  • Open a new Java project in Eclipse and save it as Arrays, and then compile and run the starter program to make sure you copied it correctly.
    package arrays;

    /**
    *
    * @author
    */
    import java.util.Scanner;
    public class Arrays {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    }

    }

  • Inside main(), add a statement to define an array named names that is suitable for holding a list of three (3) names.
  • Compile your code to make sure it has correct syntax.

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

  • Assign values to each of the array elements like:
    names[0] = "Abel Ableson";
    
  • Add a for-loop to display all three array values.
  • Compile your code to make sure it has correct syntax.

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

  • When you are finished, upload your source code to Canvas.

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 20.2: 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 
  • Submit your program to Canvas when you are finished.

       

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 20.3: 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 20.4: 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.

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


Upcoming Assignments


~See You Thursday!~