CS106A Final Exam Review Session. Saturday Dec. 10, 2016 Nick Troccoli

Similar documents
CS106A Review Session. Monday Oct. 31, 2016 Nick Troccoli

CS106A Review Session

CS 106A Midterm Review. Rishi Bedi, adapted from slides by Kate Rydberg and Nick Troccoli Summer 2017

Primitives, Objects, and Heap/Stack Review 1 Chris Piech CS106A, Stanford University

CS 106A, Lecture 27 Final Exam Review 1

YEAH Session #6. November 13, 2014, 6-7 PM Nick Troccoli

CS 106A, Lecture 27 Final Exam Review 1

Hangman YEAH Hours. Thursday, February 14, 7:30 9:00PM Andrew Tierno

YEAH session #6. 6 March 2014, 5:30p-6:30p Miles Seiver

Nested Loops Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Simple Java YEAH Hours. Brahm Capoor and Vrinda Vasavada

GPolygon GCompound HashMap

CS 106A, Lecture 11 Graphics

Memory Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Classes. How can we manage large programs?

Assignment 6 YEAH Hours. Ben Barnett and Avery Wang

October 27, 7:30-9:30 PM Taylor Bacon and Kashif Nazir (Based on slides by Nick Troccoli)

Introduction to Programming Using Java (98-388)

CS 106A, Lecture 14 Events and Instance Variables

CS 106A, Lecture 14 Events and Instance Variables

Additional Practice Problem Solutions

CS 106A, Lecture 23 Interactors and GCanvas

CS 106A, Lecture 9 Problem-Solving with Strings

Solutions to Midterm Exam

Answer Key. 1. General Understanding (10 points) think before you decide.

CS 106A, Lecture 9 Problem-Solving with Strings

Lesson 3: Accepting User Input and Using Different Methods for Output

Answers to Additional Practice Final Problems

Chapter 4 Defining Classes I

Objects and Graphics

CS 106A, Lecture 24 Interactors and NameSurfer

106A assignment review #4. 13 Feb :30p-6:30p.! Miles Seiver

HST 952. Computing for Biomedical Scientists Lecture 8

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Adapted from slides by Brahm Capoor. Breakout YEAH hours. Michael (Chung Troute)

Full file at

CS 106A Winter 2017 Final Solutions

Interactors. Brahm Capoor.

CS 106A, Lecture 19 ArrayLists

APCS Semester #1 Final Exam Practice Problems

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

CS 170 Java Programming 1. Week 9: Learning about Loops

CSC Java Programming, Fall Java Data Types and Control Constructs

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

YEAH Hours. January , 7-8 PM Jared Wolens

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Solutions to Section #7

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

1.00 Lecture 30. Sending information to a Java program

CS121/IS223. Object Reference Variables. Dr Olly Gotel

Fall 2017 CISC124 10/1/2017

Practice exam for CMSC131-04, Fall 2017

Section Handout #7: Interactors and Classes

Drawing Geometrical Objects. Graphic courtesy of Eric Roberts

CS 231 Data Structures and Algorithms Fall 2018

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CITS1001 week 4 Grouping objects lecture 2

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions

PIC 20A Streams and I/O

CS 106A, Lecture 20 ArrayLists and HashMaps

CS108, Stanford Handout #8. Java Generics

Arrays Chris Piech CS106A, Stanford University

A Guide Illustrating the Core Java Equivalent to Selected Tasks Done Using the HSA Class Library

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Announcements. Java Graphics. Exceptions. Java Odds & Ends

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

Java for Non Majors. Final Study Guide. April 26, You will have an opportunity to earn 20 extra credit points.

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CS112 Lecture: Working with Numbers

Full file at

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

You have three hours to complete this exam. There are 50 total points.

G51PGP Programming Paradigms. Lecture OO-4 Aggregation

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

CSE 143 Au04 Midterm 2 Sample Solution Page 1 of 7

Section Solutions 8. /* The separator used to delimit the start and end of a flight. */ private static final String FLIGHT_DELIMITER = " -> ";

CS 211 Programming Practicum Spring 2017

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Final Exam CS 152, Computer Programming Fundamentals December 9, 2016

Do not turn to the next page until the start of the exam.

Expressions, Statements, and Control Structures

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

COP 3330: Object Oriented Programming FALL 2017 STUDY UNION REVIEW CREDIT TO DR. GLINOS AND PROFESSOR WHITING FOR COURSE CONTENT

COP 3330: Object Oriented Programming

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

AP CS Unit 11: Graphics and Events

Lab 10: Sockets 12:00 PM, Apr 4, 2018

Pace University. Fundamental Concepts of CS121 1

Program Fundamentals

Introducing arrays. Week 4: arrays and strings. Creating arrays. Declaring arrays. Initialising arrays. Declaring and creating in one step

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Computer Science E-119 Fall Problem Set 1. Due before lecture on Wednesday, September 26

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

M257 Past Paper Oct 2008 Attempted Solution

Transcription:

CS106A Final Exam Review Session Saturday Dec. 10, 2016 Nick Troccoli 1

Today s Topic List Primitives, Objects, and Heap/Stack Graphics + Animation Event-Driven Programs Strings + chars Classes + Interfaces Arrays, ArrayLists and HashMaps File Reading 2

Primitives, Objects, and Heap/Stack 3

Primitives and Objects Primitives: int, double, boolean, char, Objects: GRect, GOval, GLine, int[], (anything with new, and that you call methods on) Treat Strings as primitives 4

Parameters When passing parameters, make a copy of whatever is on the stack. Primitives: the actual value is on the stack (pass by value) Objects: a heap address where the information lives is on the stack. (pass by reference) 5

Parameters - Primitives public void run() { int x = 2; addtwo(x); println(x); // x is still 2! private void addtwo(int y) { y += 2; 6

Parameters - Objects public void run() { GRect rect = new Grect(0,0,50,50); fillblue(rect); add(rect); // rect is blue! private void fillblue(grect rect) { rect.setfilled(true); rect.setcolor(color.blue); 7

Program Traces Approaching program traces Local variables are separate across methods Parameters are just assigned names by the order in which they re passed Write values above variable names as you go through the program (or draw stack frame boxes) Pass-by-reference vs. pass-by-value 8

0 1 2 3 4 5 Input to mystery() What is arr after? Take 1 9

0 1 2 3 4 5 Input to mystery() What is arr after? Take 2 10

Graphics and Animation 11

Graphics Look at lecture slides for lists of different GObject types and their methods Remember: the x and y of GRect, GOval, etc. is their upper left corner, but the x and y of GLabel is its leftmost baseline coordinate. Remember: a label s height is gotten from getascent. 12

Animation Standard format for animation code: while (CONDITION) { updategraphics(); performchecks(); pause(pause_time); 13

Event Driven Programs 14

Events Three types of events: keyboard, mouse, interactors Two ways for Java to execute your code: from run() and from event handlers (mouseclicked, mousemoved, actionperformed, etc.) These programs are asynchronous; your code is not run in order anymore, since you don t know when the user will interact with your program! 15

Mouse + Key Events 1. Sign up for notifications for key or mouse events 2. Implement the method corresponding to what event you care about (e.g. mousepressed, mousemoved) 3. Java will call that method whenever the corresponding event occurs. 16

Interactors 1. Add interactors in init() 2. addactionlisteners() to listen for button presses 3..addActionListener(this) on text fields for ENTER 4. Implement actionperformed 5. Java will call actionperformed whenever an action event occurs. 17

Interactors public void actionperformed(actionevent e) { if (e.getactioncommand().equals( My Button )) {... //... equivalent to... public void actionperformed(actionevent e) { if (e.getsource() == myjbutton) {... 18

Holiday Lights! 19

Holiday Lights Add a new holiday light by clicking Add Light Every second, every light on screen changes to a new random color 20

Instance Variables 21

init() 22

run() 23

public void actionperformed(actionevent e) { if (e.getactioncommand().equals("add Light )) { GOval bulb = new GOval(2*BULB_H_RADIUS, 2*BULB_V_RADIUS); bulb.setfilled(true); bulb.setcolor(color.red); GRect base = new GRect(BULB_BASE_SIZE, BULB_BASE_SIZE); base.setfilled(true); base.setcolor(color.black); int x = rgen.nextint(0, getwidth()); int y = rgen.nextint(0, getheight()); add(bulb, x BULB_H_RADIUS, y); add(base, x - BULB_BASE_SIZE / 2.0, y + 2*BULB_V_RADIUS); bulbs.add(bulb);

public void actionperformed(actionevent e) { if (e.getactioncommand().equals("add Light )) { GOval bulb = new GOval(2*BULB_H_RADIUS, 2*BULB_V_RADIUS); bulb.setfilled(true); bulb.setcolor(color.red); GRect base = new GRect(BULB_BASE_SIZE, BULB_BASE_SIZE); base.setfilled(true); base.setcolor(color.black); int x = rgen.nextint(0, getwidth()); int y = rgen.nextint(0, getheight()); add(bulb, x BULB_H_RADIUS, y); add(base, x - BULB_BASE_SIZE / 2.0, y + 2*BULB_V_RADIUS); bulbs.add(bulb);

public void actionperformed(actionevent e) { if (e.getactioncommand().equals("add Light )) { GOval bulb = new GOval(2*BULB_H_RADIUS, 2*BULB_V_RADIUS); bulb.setfilled(true); bulb.setcolor(color.red); GRect base = new GRect(BULB_BASE_SIZE, BULB_BASE_SIZE); base.setfilled(true); base.setcolor(color.black); int x = rgen.nextint(0, getwidth()); int y = rgen.nextint(0, getheight()); add(bulb, x BULB_H_RADIUS, y); add(base, x - BULB_BASE_SIZE / 2.0, y + 2*BULB_V_RADIUS); bulbs.add(bulb);

public void actionperformed(actionevent e) { if (e.getactioncommand().equals("add Light )) { GOval bulb = new GOval(2*BULB_H_RADIUS, 2*BULB_V_RADIUS); bulb.setfilled(true); bulb.setcolor(color.red); GRect base = new GRect(BULB_BASE_SIZE, BULB_BASE_SIZE); base.setfilled(true); base.setcolor(color.black); int x = rgen.nextint(0, getwidth()); int y = rgen.nextint(0, getheight()); add(bulb, x BULB_H_RADIUS, y); add(base, x - BULB_BASE_SIZE / 2.0, y + 2*BULB_V_RADIUS); bulbs.add(bulb);

public void actionperformed(actionevent e) { if (e.getactioncommand().equals("add Light )) { GOval bulb = new GOval(2*BULB_H_RADIUS, 2*BULB_V_RADIUS); bulb.setfilled(true); bulb.setcolor(color.red); GRect base = new GRect(BULB_BASE_SIZE, BULB_BASE_SIZE); base.setfilled(true); base.setcolor(color.black); int x = rgen.nextint(0, getwidth()); int y = rgen.nextint(0, getheight()); add(bulb, x BULB_H_RADIUS, y); add(base, x - BULB_BASE_SIZE / 2.0, y + 2*BULB_V_RADIUS); bulbs.add(bulb);

public void actionperformed(actionevent e) { if (e.getactioncommand().equals("add Light )) { GOval bulb = new GOval(2*BULB_H_RADIUS, 2*BULB_V_RADIUS); bulb.setfilled(true); bulb.setcolor(color.red); GRect base = new GRect(BULB_BASE_SIZE, BULB_BASE_SIZE); base.setfilled(true); base.setcolor(color.black); int x = rgen.nextint(0, getwidth()); int y = rgen.nextint(0, getheight()); add(bulb, x BULB_H_RADIUS, y); add(base, x - BULB_BASE_SIZE / 2.0, y + 2*BULB_V_RADIUS); bulbs.add(bulb);

public void actionperformed(actionevent e) { if (e.getactioncommand().equals("add Light )) { GOval bulb = new GOval(2*BULB_H_RADIUS, 2*BULB_V_RADIUS); bulb.setfilled(true); bulb.setcolor(color.red); GRect base = new GRect(BULB_BASE_SIZE, BULB_BASE_SIZE); base.setfilled(true); base.setcolor(color.black); int x = rgen.nextint(0, getwidth()); int y = rgen.nextint(0, getheight()); add(bulb, x BULB_H_RADIUS, y); add(base, x - BULB_BASE_SIZE / 2.0, y + 2*BULB_V_RADIUS); bulbs.add(bulb);

public void actionperformed(actionevent e) { if (e.getactioncommand().equals("add Light )) { GOval bulb = new GOval(2*BULB_H_RADIUS, 2*BULB_V_RADIUS); bulb.setfilled(true); bulb.setcolor(color.red); GRect base = new GRect(BULB_BASE_SIZE, BULB_BASE_SIZE); base.setfilled(true); base.setcolor(color.black); int x = rgen.nextint(0, getwidth()); int y = rgen.nextint(0, getheight()); add(bulb, x BULB_H_RADIUS, y); add(base, x - BULB_BASE_SIZE / 2.0, y + 2*BULB_V_RADIUS); bulbs.add(bulb);

Strings and chars 32

Strings and chars A char is a primitive type that represents a single letter, digit, or symbol. Uses single quotes ( ). Computers represent chars as numbers under the hood (ASCII encoding scheme). A string is an immutable object that represents a sequence of characters. Uses double quotes ( ). 33

chars char uppercasea = A ; char uppercaseb = (char)(uppercasea + 1); int lettersinalphabet = Z A + 1; // equivalent: z a + 1 // A to Z and a to z are sequential numbers. 34

Characters Problem: we can t call methods on chars or store them in collections since they re primitives! Solution: the Character class Call methods on the Character class and pass the char as a parameter. 35

Characters 36

Characters and chars char ch = a ; Character.toUpperCase(ch); // does nothing! ch.touppercase(); // won t compile! ch = Character.toUpperCase(ch); // if (Character.isUpperCase(ch)) { println(ch + is upper case! ); 37

Strings Strings are (immutable) objects. This means we can call methods on them! We cannot change a string after creating it. Strings can be combined with ints, doubles, chars, etc. 38

Strings are Immutable! String str = Hello ; str += world ; // what is actually happening: String str = Hello ; str = str + world ; // This makes a NEW string on the right, and // then re-assigns str to equal it! 39

Helpful String Methods 40

Helpful String Methods String str = Hello world! ; str.touppercase(); str = str.touppercase(); // no new needed // does nothing! // for (int i = 0; i < str.length(); i++) { println(str.charat(i)); // prints each char on its own line 41

Putting it All Together String str = happy holidays ; String newstr = ; for (int i = 0; i < str.length(); i++) { char ch = str.charat(i); if (i % 2 == 0) ch = Character.toUpperCase(ch); newstr += ch; // newstr = HaPpY HoLiDaYs 42

Type Conversion println( B + 8 + 4); // prints B84 println( B + (8 + 4)); // prints B12 println( A + 5 + ella ); // prints 70ella (note: A corresponds to 65) println((char)( A + 5) + ella ); // prints Fella 43

Type Conversion This seems nonsensical - but it s not! (kind of) Just use precedence rules and keep track of the type along the way. println( A + 5 + ella ); // A + 5 is int (70), int + ella is string println((char)( A + 5) + ella ); // A + 5 is char ( F ), char + ella is string 44

String Tokenizers Chop up a string according to certain delimiters. Use hasmoretokens() to check if there are more tokens. Use nexttoken() to get the next token. Optional last parameter in constructor says whether or not to include delimiters as tokens too. StringTokenizer t = new StringTokenizer(str, ; ); StringTokenizer t = new StringTokenizer(str, ;, true); 45

Strings Practice Lets write a method that, given a string, returns its acronym. "In Real Life" -> I.R.L. "All Day I Dream About Soccer " -> A.D.I.D.A.S. "Come Late And Start Sleeping " -> C.L.A.S.S. "Come Late And then you Start Sleeping " -> C.L.A.S.S. Every capitalized word contributes one letter to the acronym. 46

Practice: Acronyms private String acronym(string str) { String acronym = ""; StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasmoretokens()) { String token = tokenizer.nexttoken(); if (Character.isUpperCase(token.charAt(0))) { acronym += token.charat(0) + "."; return acronym; 47

Practice: Acronyms private String acronym(string str) { String acronym = ""; StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasmoretokens()) { String token = tokenizer.nexttoken(); if (Character.isUpperCase(token.charAt(0))) { acronym += token.charat(0) + "."; return acronym; 48

Practice: Acronyms private String acronym(string str) { String acronym = ""; StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasmoretokens()) { String token = tokenizer.nexttoken(); if (Character.isUpperCase(token.charAt(0))) { acronym += token.charat(0) + "."; return acronym; 49

Practice: Acronyms private String acronym(string str) { String acronym = ""; StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasmoretokens()) { String token = tokenizer.nexttoken(); if (Character.isUpperCase(token.charAt(0))) { acronym += token.charat(0) + "."; return acronym; 50

Practice: Acronyms private String acronym(string str) { String acronym = ""; StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasmoretokens()) { String token = tokenizer.nexttoken(); if (Character.isUpperCase(token.charAt(0))) { acronym += token.charat(0) + "."; return acronym; 51

Practice: Acronyms private String acronym(string str) { String acronym = ""; StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasmoretokens()) { String token = tokenizer.nexttoken(); if (Character.isUpperCase(token.charAt(0))) { acronym += token.charat(0) + "."; return acronym; 52

Practice: Acronyms private String acronym(string str) { String acronym = ""; StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasmoretokens()) { String token = tokenizer.nexttoken(); if (Character.isUpperCase(token.charAt(0))) { acronym += token.charat(0) + "."; return acronym; 53

Practice: Acronyms private String acronym(string str) { String acronym = ""; StringTokenizer tokenizer = new StringTokenizer(str); while (tokenizer.hasmoretokens()) { String token = tokenizer.nexttoken(); if (Character.isUpperCase(token.charAt(0))) { acronym += token.charat(0) + "."; return acronym; 54

Classes + Interfaces 55

Classes A class is a way to tell Java about a new variable type, AKA define a new class of object. To do that, you must define what information that type of object contains (instance variables), and what it can do (methods). E.g. NameSurferEntry, HangmanCanvas 56

Constructors Every class has (at least) one constructor. A constructor is the special method called when a new instance of your class is first created. You can have multiple constructors that take different arguments. GRect rect = new GRect(0, 0, 50, 50); GRect rect2 = new GRect(50, 50); 57

Interfaces An interface is a list of method names (no implementations!). Any class can implement an interface, which means they provide an implementation of every method in the interface. Interfaces let different classes tell Java they implement the same behavior. (e.g. GFillable) Interfaces let each class implement methods their own way. 58

Practice: Airplane! Let s write a class Airplane that implements the Boardable interface Airplane is initialized with its capacity. Don t worry about error-checking. public interface Boardable { /** Boards a single passenger, at front or back **/ public void boardpassenger(string name, boolean priority); /** Returns whether the vehicle is full **/ public boolean isfull(); /** Unboards/returns next passenger **/ public String unboardpassenger(); 59

Practice: Airplane! Need an ArrayList of passenger names Need an int to store the maximum capacity 60

Practice: Airplane! public class Airplane implements Boardable { private ArrayList<String> passengers; private int capacity; public Airplane(int numseats) { passengers = new ArrayList<String>(); capacity = numseats;... 61

boardpassenger public void boardpassenger(string name, boolean priority) {... if (priority) { passengers.add(0, name); else { passengers.add(name); 62

isfull public boolean isfull() { return capacity == passengers.size();... 63

unboardpassenger public String unboardpassenger() { return passengers.remove(0); 64

Practice: Airplane! https://youtu.be/wvdncdvmrpo 65

Arrays, ArrayLists and HashMaps 66

Arrays An array is a fixed-length list of a single type of thing. An array can store primitives and objects. You cannot call methods on it. I.e. no array.contains(). Get the length by saying.length. (No parentheses!) 67

ArrayLists An ArrayList is a flexible-length list of a single type of thing. An ArrayList can only store objects. Uses wrapper classes to store primitives (e.g. Character, Integer, Double). An ArrayList has a variety of methods you can use, including.contains,.get,.remove,.add, etc. 68

HashMaps A HashMap is an unordered bag of key-value pairs. A HashMap can only store objects as keys and values. Uses wrapper classes to store primitives (e.g. Character, Integer, Double). A HashMap s keys are unique. A HashMap has a variety of methods you can use, including.containskey,.put,.get, etc. 69

Which Do I Use? Ordered list? -> array or ArrayList Any mapping from one thing to another -> HashMap Expandable list -> ArrayList 70

Iterators An iterator is an object that lets you iterate over every value in a collection (e.g. ArrayList, HashMap). Similar to StringTokenizer: hasnext(), next() Lets you iterate over a list without having access to the list itself. 71

Iterators - ArrayList Iterator<String> = mylist.iterator(); while (it.hasnext()) { println(it.next()); // Note: in order 72

Iterators - HashMap Iterator<String> = mymap.keyset().iterator(); while (it.hasnext()) { String key = it.next(); println(key + -> + mymap.get(key)); // Note: unknown order! 73

Collections Practice Let s write a console program to keep track of what gifts you re getting your friends. The program should allow a user to enter a name, followed by one gift to get for them. You may only add one gift at a time, but may add a gift for a person multiple times. Once the user is done, you should print out each person followed by what gifts to get them. 74

Practice: GiftList public void run() { HashMap<String, ArrayList<String>> giftmap = new HashMap<String, ArrayList<String>>(); println( Welcome to GiftList! Enter a name, ); println( followed by a gift. Just ENTER to quit. );... 75

Practice: GiftList while (true) { String name = readline( Name? ); if (name.equals( )) break; String gift = readline( Gift? );... ArrayList<String> giftlist; if (giftmap.containskey(name)) { giftlist = giftmap.get(name); else giftlist = new ArrayList<String>(); 76

Practice: GiftList while (true) { String name = readline( Name? ); if (name.equals( )) break; String gift = readline( Gift? );... ArrayList<String> giftlist; if (giftmap.containskey(name)) { giftlist = giftmap.get(name); else giftlist = new ArrayList<String>(); 77

Practice: GiftList while (true) { String name = readline( Name? ); if (name.equals( )) break; String gift = readline( Gift? );... ArrayList<String> giftlist; if (giftmap.containskey(name)) { giftlist = giftmap.get(name); else giftlist = new ArrayList<String>(); 78

Practice: GiftList while (true) { String name = readline( Name? ); if (name.equals( )) break; String gift = readline( Gift? );... ArrayList<String> giftlist; if (giftmap.containskey(name)) { giftlist = giftmap.get(name); else giftlist = new ArrayList<String>(); 79

Practice: GiftList giftlist.add(gift); giftmap.put(name, giftlist); println(giftmap.tostring()); 80

File Reading 81

File Reading Use a BufferedReader to read in a text file. try/catch try this, and catch the error if something happens BufferedReaders are like StringTokenizers; they can only give you the next line in the file. Remember to close your BufferedReader when you re done! 82

File Reading try { BufferedReader rd = new BufferedReader(new FileReader(filename)); while (true) { String line = rd.readline(); if (line == null) break; println( Read line: [ + line + ] ); rd.close(); catch (IOException ex) { throw new ErrorException(ex); 83

Practice: GuestList Let s say we re given a guest list for a party. The guest list is formatted as follows: Specifically, each line has the name of a friend, and how many people they are bringing. Print out the friend bringing the most people. 84

String maxname = ; int maxguests = 0; try { BufferedReader rd = new BufferedReader(new FileReader( guestlist.txt )); while (true) {... String line = rd.readline(); if (line == null) break; StringTokenizer t = new StringTokenizer(line, ); String name = t.nexttoken().trim(); int numguests = Integer.parseInt(t.nextToken().trim()); if (numguests > maxguests) { maxguests = numguests; maxname = name; 85

String maxname = ; int maxguests = 0; try { BufferedReader rd = new BufferedReader(new FileReader( guestlist.txt )); while (true) {... String line = rd.readline(); if (line == null) break; StringTokenizer t = new StringTokenizer(line, ); String name = t.nexttoken().trim(); int numguests = Integer.parseInt(t.nextToken().trim()); if (numguests > maxguests) { maxguests = numguests; maxname = name; 86

String maxname = ; int maxguests = 0; try { BufferedReader rd = new BufferedReader(new FileReader( guestlist.txt )); while (true) {... String line = rd.readline(); if (line == null) break; StringTokenizer t = new StringTokenizer(line, ); String name = t.nexttoken().trim(); int numguests = Integer.parseInt(t.nextToken().trim()); if (numguests > maxguests) { maxguests = numguests; maxname = name; 87

String maxname = ; int maxguests = 0; try { BufferedReader rd = new BufferedReader(new FileReader( guestlist.txt )); while (true) {... String line = rd.readline(); if (line == null) break; StringTokenizer t = new StringTokenizer(line, ); String name = t.nexttoken().trim(); int numguests = Integer.parseInt(t.nextToken().trim()); if (numguests > maxguests) { maxguests = numguests; maxname = name; 88

String maxname = ; int maxguests = 0; try { BufferedReader rd = new BufferedReader(new FileReader( guestlist.txt )); while (true) {... String line = rd.readline(); if (line == null) break; StringTokenizer t = new StringTokenizer(line, ); String name = t.nexttoken().trim(); int numguests = Integer.parseInt(t.nextToken().trim()); if (numguests > maxguests) { maxguests = numguests; maxname = name; 89

String maxname = ; int maxguests = 0; try { BufferedReader rd = new BufferedReader(new FileReader( guestlist.txt )); while (true) {... String line = rd.readline(); if (line == null) break; StringTokenizer t = new StringTokenizer(line, ); String name = t.nexttoken().trim(); int numguests = Integer.parseInt(t.nextToken().trim()); if (numguests > maxguests) { maxguests = numguests; maxname = name; 90

String maxname = ; int maxguests = 0; try { BufferedReader rd = new BufferedReader(new FileReader( guestlist.txt )); while (true) {... String line = rd.readline(); if (line == null) break; StringTokenizer t = new StringTokenizer(line, ); String name = t.nexttoken().trim(); int numguests = Integer.parseInt(t.nextToken().trim()); if (numguests > maxguests) { maxguests = numguests; maxname = name; 91

rd.close(); println(maxname + is bringing the most guests. ); catch (IOException ex) { throw new ErrorException(ex); 92

Wrap-up 93

Wrap-up Try to get to every problem Don t rush to coding too quickly Pseudocode! Look over practice final, extra problems, section handouts, and book for more practice Think about how much you ve learned in 10 weeks! 94