To Lecture Notes

IT 313 -- Jan 30, 2020

Review Exercises

  1. Name four possible input sources for a Scanner object.
    Ans: Keyboard, from a file, from the web, from a String. See the InputOutput Example.
  2. Create an ArrayList collection that contains three Person objects. See the person module in the Classes Example. Ans:
    public static void main(String[ ] args) {
        ArrayList<Person> col =
            new ArrayList< >(500);
        Person p1 = new Person("Alice", 'F', 21);
        Person p2 = new Person("Barry", 'M', 25);
        Person p3 = new Person("Chloe", 'F', 19);
        col.add(p1);
        col.add(p2);
        col.add(p3);
        System.out.println(col);
    }
    
  3. Modify Exercise 2 to populate the collection with person data read from an input file.
    Ans: Here are the contents of the input file persons.txt:
    Alice,F,21
    Barry,M,25
    Chloe,F,19
    Danielle,F,27
    
    Here is the main method. It was modified to use a try/catch block (see the Catching Exceptions section below). We used the IntelliJ shortcut Alt-Insert to write the try/catch block:
     public static void main(String[ ] args) {
    
        File f = new File("persons2.txt");
        Scanner s = null;
        try {
            s = new Scanner(f);
        } 
        catch (FileNotFoundException e) {
            System.out.println("File not found.");
            System.exit(1);
        }
    
        ArrayList<Person> col = new ArrayList< >(50);
        while(s.hasNextLine( )) {
            String line = s.nextLine( );
            String[ ] fields = line.split(",");
            String name = fields[0].strip( );
            char gender = fields[1].strip( ).charAt(0);
            int age = Integer.parseInt(fields[2].strip( ));
            Person p = new Person(name, gender, age);
            col.add(p);
        }
        s.close( );
        System.out.println(col);
    }
    

Project 4

Wrapper Classes

Catching Exceptions

Packages

Review of Inheritance

JAR Files