6 Pages

30a-section-5-solutions

Course: CS 106A, Fall 2011
School: Stanford
Rating:
 
 
 
 
 

Word Count: 889

Document Preview

Sahami CS Mehran 106A Handout #30A November 2, 2011 Solution to Section #5 Portions of this handout by Eric Roberts 1. Word count /* * File: WordCount.java * -------------------* Counts the characters, words, and lines in a file. */ import acm.program.*; import java.io.*; public class WordCount extends ConsoleProgram { public void run() { int lines = 0; int words = 0; int chars = 0; BufferedReader rd =...

Register Now

Unformatted Document Excerpt

Coursehero >> California >> Stanford >> CS 106A

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Sahami CS Mehran 106A Handout #30A November 2, 2011 Solution to Section #5 Portions of this handout by Eric Roberts 1. Word count /* * File: WordCount.java * -------------------* Counts the characters, words, and lines in a file. */ import acm.program.*; import java.io.*; public class WordCount extends ConsoleProgram { public void run() { int lines = 0; int words = 0; int chars = 0; BufferedReader rd = openFileReader("File: "); try { while (true) { String line = rd.readLine(); if (line == null) break; lines++; words += countWords(line); chars += line.length(); } rd.close(); } catch (IOException ex) { println("An I/O exception has occurred"); } println("Lines = " + lines); println("Words = " + words); println("Chars = " + chars); } /** * Asks the user for the name of an input file and returns a * BufferedReader attached to its contents. If the file does * not exist, the user is given another chance to try. */ private BufferedReader openFileReader(String prompt) { BufferedReader rd = null; while (rd == null) { String name = readLine(prompt); try { rd = new BufferedReader(new FileReader(name)); } catch (IOException ex) { println("Can't open that file."); } } return rd; } 2 /** * Counts the words (consecutive strings of letters and/or digits) * in the input line. */ private int countWords(String line) { boolean inWord = false; int words = 0; for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (Character.isLetterOrDigit(ch)) { inWord = true; } else { if (inWord) words++; inWord = false; } } if (inWord) words++; return words; } } 2. How Unique! /* * File: UniqueNames.java * ---------------------* This program asks the user for a list of names (one per line) * until the user enters a blank line. Then the program prints * out the list of names entered, where each name is listed only * once (i.e., uniquely) */ public class UniqueNames extends ConsoleProgram { public void run() { ArrayList<String> list = new ArrayList<String>(); while (true) { String name = readLine("Enter name: "); if (name.equals("")) break; if (!list.contains(name)) { list.add(name); } } println("Unique name list contains:"); printList(list); } /* Prints out contents of ArrayList, one element per line */ private void printList(ArrayList list) { for(int i = 0; i < list.size(); i++) { println(list.get(i)); } } } 3 3. A Christmas Carol /** * File: Employee.java * ---------------------* Class which describes the Employee variable type. */ public class Employee { public Employee(String newName, int newId) { name = newName; taxId = newId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public String getName() { return name; } public int getTaxId() { return taxId; } /* Employee instance variables */ String name; int taxId; String title; boolean active; int salary; } 4 /** * File ChristmasCarol.java * -----------------------* Counts the words (consecutive strings of letters and/or digits) * in the input line. */ public class ChristmasCarol ConsoleProgram{ public extends void run() { Employee ceo = new Employee(Ebenezer Scrooge, 161803399); Employee partner = new Employee(Jacob Marley, 271828182); Employee clerk = new Employee(Bob Cratchit, 314159265); ceo.setTitle(Ceo); partner.setTitle(Former Partner); clerk.setTitle(Clerk); ceo.setActive(true); partner.setActive(false); clerk.setActive(true); ceo.setSalary(1000); partner.setSalary(0); clerk.setSalary(25); } } } 4. Histogram /* * File: Histogram.java * -------------------* This program reads a list of exam scores, with one score per line. * It then displays a histogram of those scores, divided into the * ranges 09, 1019, 2029, and so forth, up to the range containing * only the value 100. */ import acm.program.*; import acm.util.*; import java.io.*; public class Histogram extends ConsoleProgram { public void run() { initHistogram(); readScoresIntoHistogram(); printHistogram(); } /* Initializes the histogram array */ private void initHistogram() { histogramArray = new int[11]; for (int i = 0; i <= 10; i++) { histogramArray[i] = 0; } } 5 /* Reads the exam scores, updating the histogram */ private void readScoresIntoHistogram() { try { BufferedReader rd = new BufferedReader(new FileReader(DATA_FILE)); while (true) { String line = rd.readLine(); if (line == null) break; int score = Integer.parseInt(line); if (score < 0 || score > 100) { throw new ErrorException("That score is out of range"); } else { int range = score / 10; histogramArray[range]++; } } } catch (IOException ex) { throw new ErrorException(ex); } } /* Displays the histogram */ private void printHistogram() { for (int range = 0; range <= 10; range++) { String label; switch (range) { case 0: label = "00-09"; break; case 10: label = " 100"; break; default: label = (10 * range) + "-" + (10 * range + 9); break; } String stars = createStars(histogramArray[range]); println(label + ": " + stars); } } /* Creates a string consisting of n stars */ private String createStars(int n) { String stars = ""; for (int i = 0; i < n; i++) { stars += "*"; } return stars; } /* Private instance variables */ private int[] histogramArray; /* Name of the data file */ private static final String DATA_FILE = "MidtermScores.txt"; } 6 5. Tracing method execution The output of Halloween.java is: skellington 10 Syle Focus for Section 5: Writing our Own Classes In this section we wrote our own Employee class. In our class we wrote several getter and setter methods. A getter method is one where we can access the value of a private data member, and a setter method is where we provide access for the client to set the value. We use getters and setters instead of making our instance variables public because we do not want to give other classes direct access, or we may not want them changing every variable. This is a common pattern in object-oriented programming. You should also not the naming conventions we use suchg as getName(). This is a standard way to name a getter method, where we write get and then the name of our variable. Another important part of the class is choosing the instance variables. What are the things that define an Employee? Each one has its own name, salary, etc. These are usually the instance variables.
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Stanford - CS - 106A
Mehran SahamiCS 106AHandout #31October 31, 2011Exam StrategiesBased on a handout originally written by Julie Zelinski and Chris PiechThe exams in the CS106 courses can be challenging and even a bit intimidating. Hopefully youhave been keeping up in
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #32October 31, 2011ArrayLists Reference for HangmanBased on a handout by Patrick YoungThis handout gives you a quick reference for some of the concepts related to ArrayListsthat may be useful to you for implementing Part
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #33November 7, 2011Solutions to Midterm ExamProblem 1: Karel the Robot/* File: MountainKarel.java */import stanford.karel.*;public class MountainKarel extends SuperKarel cfw_public void run() cfw_goToMountain();climb
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #34November 7, 2011DebuggingThanks to Eric Roberts and Nick Parlante for portions of this handout.Much of your time as a computer programmer will likely be spent debugging. Thisphenomenon is best described by a quotation
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #35November 7, 2011Section Handout #6: More Arrays and HashMapsPortions of this handout by Eric Roberts1. How Prime!In the third century B.C., the Greek astronomer Eratosthenes developed an algorithm forfinding all the
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #35ANovember 9, 2011Solutions to Section #61. How Primepublic class SieveOfEratosthenes extends ConsoleProgram cfw_private static final int UPPER_LIMIT = 1000;public void run() cfw_boolean[] resolved = new boolean[UPPE
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #36November 7, 2011Assignment #5 Yahtzee!Due: 3:15pm on Wednesday, November 16thYour Early Assignment Help (YEAH) hours:8:00pm-10:00pm, Monday, Nov. 7th in Braun Lecture Hall (Mudd Chemistry Bldg.)Based on a handout wri
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #37November 9, 2011CS 106A Graphics ContestSubmission deadline: 11:59pm on Saturday, December 3rdBased on a handout by Eric RobertsThe graphics programs you write using the acm.graphics package tend to be moreexciting t
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #38November 14, 2011Example programs showing interactor usageFile: InteractiveDrawFace.java/** File: InteractiveDrawFace.java* -* This program draws GFaces on the screen, but allows the* use to modify their size and co
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #39November 14, 2011Section Handout #7: Using InteractorsBased on a handout by Eric Roberts1. Using InteractorsThe purpose of this problem is to give you some practice using the kind of interactors youneed for the NameS
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #39ANovember 16, 2011Solution to Section #7Based on a handout by Eric Roberts1. Using Interactors/ File: BoxDiagram.java/ This program allows the user to create a set of boxes with labels/ and then drag them around in
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #40November 16, 2011Assignment #6NameSurferDue: 3:15pm on Wednesday, November 30thYEAH hours: 8:00pm-10:00pm, Wednesday, Nov. 16th in Braun Lecture HallThe NameSurfer assignment was created by Nick Parlante and further r
Stanford - CS - 106A
Mehran SahamiCS 106AHandout #41November 16, 2011MusicShop Program (ComponentListener Example)File: MusicShop.java/** File: MusicShop.java* -* This program handles the data management for a music* shop, showing which albums are carried and how man
Iowa State - PHYSICS - 112
CLASS EXERCISE # 1 - 13 June 20051. (2 points) Determine the B and C components of a vector of magnitude 4.7 m in a direction 35 west of north. Be sure to include the correct signs! The angle of this vector is ) oe 90 35 oe 125 The B component is E cos )
Iowa State - PHYSICS - 112
CLASS EXERCISE #2 - 14 June 2005The diagram below shows three charges which are identical in magnitude (same number of coulombs), one of which is positive and the other two negative S is positive, &lt; is negative. The middle charge is exactly halfway betwe
Iowa State - PHYSICS - 112
CLASS EXERCISE #3 - 15 June 2005Consider the electrical force between pairs of electric charges as shown. These are three independent problems, with different charges but the same separation &lt; in each case. U represents the same number of coulombs in eac
Iowa State - PHYSICS - 112
CLASS EXERCISE #4 - 16 June 2005Here are some statements about the electric force. Determine if each is true or false. If false, explain why, by giving a counterexample or correcting the statement. (1) The electric force between two electric charges is a
Iowa State - PHYSICS - 112
CLASS EXERCISE #5 - 20 June 2005(1) Suppose that the electric field at a certain point is t I oe ( 1000 N/C, 500 N/C). (a) What is the electric force produced by that field on a charge of 15 .C? t t J oe ;I oe 15 , 106 C 1000 N/C, 500 N/C oe 0.015 N, 0.0
Iowa State - PHYSICS - 112
CLASS EXERCISE #6 - June 21, 2005 (1) When two charges are separated by 4.0 m, their electric potential energy is 12 J. What can you tell, if anything, about the signs of these two charges? Since the electric potential energy is positive, the two charges
Iowa State - PHYSICS - 112
CLASS EXERCISE # 7 - 27 JUNE 2005V 5H 3H 3H M 3A 2A 4A ?Z 15 V 6V 12 VAnswer these questions using Ohm's law and also fill out the table above: (1) Determine the potential difference across a 5-ohm resistor through which a current of 3 amperes is flowin
Iowa State - PHYSICS - 112
CLASS EXERCISE #8 - 28 June 2005(a) What is the equivalent voltage of this circuit? The two batteries face the same way, so the equivalent voltage is the sum of their voltages: 6 V 12 V oe 18 V. (b) What is the equivalent resistance of this circuit? The
Iowa State - PHYSICS - 112
CLASS EXERCISE #9 - 29 June 2005An electric circuit consists of a 23-V battery and a 4-V battery facing in opposite directions and two resistors, one 3 ohms and the other 2 ohms, all in series.(a) Draw this circuit, determine the current in this circuit
Iowa State - PHYSICS - 112
CLASS EXERCISE #11 - 5 July 2005(1) Consider the six mutually-perpendicular directions north, east, south, west, up, and down. Determine the direction of the magnetic force on a current segment for these cases: (a) Current is north, magnetic field is eas
Iowa State - PHYSICS - 112
CLASS EXERCISE #12 - 7 July 2005On your sheet, draw square or rectangular circuits (like this: ) with the current indicated and a uniform magnetic field shown. Then determine and show the direction of the force ( , , , , , OE or 0 if no force) on each si
Iowa State - PHYSICS - 112
Class Exercise #15 - 13 July 2005A circuit loop with cross-sectional area 0.060 m2 and resistance t H is shown in a uniform external magnetic field F of initial magnitude 0.5 T. t OE F ext (a) Determine the initial magnitude of the magnetic flux through
Iowa State - PHYSICS - 112
CLASS EXERCISE #16 - BASTILLE DAY(a) What is the direction of the magnetic field of the wave at that point at that time? t Using the right-hand rule with t north and I up, the magnetic field must be in the east direction. (b) What is the wavelength of th
Iowa State - PHYSICS - 112
CLASS EXERCISE #17 - 18 July 2005Light at an angle of incidence of 40 strikes a horizontal interface between water (8 oe 1.33) and glass (8 oe 1.50), coming from the water side. (a) Draw a diagram showing the incident ray and then sketch the reflected an
Iowa State - PHYSICS - 112
CLASS EXERCISE #18 - 19 July 2005A spherical mirror has a radius of curvature of 20 cm. An object is placed on the principal axis on the concave side a distance of 5.0 cm from the vertex of the mirror. Determine the focal length of this mirror and then m
Iowa State - PHYSICS - 112
CLASS EXERCISE #19 - 20 July 2005You are supposed to make a slide projector using a single convergent lens. The projector projects an image of a slide (which is placed near the lens, in the projector). Suppose you want the slide to be magnified 100 times
Iowa State - PHYSICS - 112
CLASS EXERCISE #20 - 25 July 2005Light of wavelength 500 nm is incident on a pair of slits. On a screen 2.0 m away, the interference maxima are found to be 2.0 mm apart. (a) Determine the angle ) (in radians and in degrees) corresponding to the first int
Iowa State - PHYSICS - 112
CLASS EXERCISE #22 - 27 July 2005Initially unpolarized light passes through four different polarizers, all of them letting through light polarized in a horizontal plane (like polarizers sitting on an overhead projector). The first lets through light pola
Iowa State - PHYSICS - 112
CLASS EXERCISE #23 - 28 July 2005Light of wavelength 520 nm is incident normally (perpendicularly) from air onto an interface with a thin oil film (8 oe 1.30) that is floating on water (8 oe 1.33). (a) What is the frequency of this light?0 oe - oe 3 , 1
Iowa State - PHYSICS - 112
CLASS EXERCISE #24 - 1 August 2005 An atom undergoes a transition from a state of energy 14.7 eV to a state of energy 10.6 eV. Determine whether a photon was absorbed or emitted, and determine that photon's energy (in both eV and joules) and frequency. Th
Iowa State - PHYSICS - 112
PHYSICS 112 - EXAM 4 (first part of final exam) - FALL 2003 Name _ Section _Use only a right-handed coordinate system ( B C D along thumb, forefinger, and middle finger of your right hand when these three fingers are perpendicular to one another). Show y
Iowa State - PHYSICS - 112
P-1PHYSICS 112 SUMMER 2005 Homework for June 14, 2005 Due in recitation during the first five minutes; after that, worth only 50% as much.Name SectionIn parts (1a) through (1c), consider the two dimensionless vectors t t E oe (3.10, 2.40) and F oe ( 3.
Iowa State - PHYSICS - 112
Homework Assignment #2 - Thursday June 16, 20051. (a) On a piece of graph paper (remember that some are available on the course web page) place a 3 .C charge at the origin and a 2.C at the point B oe 3.0 m C oe 0. (b) Determine the magnitude of the elect
Iowa State - PHYSICS - 112
HOMEWORK #3 for Tuesday, June 21, 2005Name _ Section _ 1. A 4-.C charge is located at the point (0 m, 3 m), and a 5-.C charge is located at the point (0 m, 2 m). No other charges are around.A. What is the magnitude of the electrical force on the 4-.C ch
Iowa State - PHYSICS - 112
Homework #4 for Thursday, June 23, 2005Name _ Section _The figure above shows a (rectangular) region of space with a uniform magnetic field: the electric field everywhere has the same magnitude and direction. The direction of the electric field is indic
Iowa State - PHYSICS - 112
HOMEWORK - TUESDAY, JUNE 28, 20051. A piece of an electric circuit consists of five resistors connected as shown below. The electric potential at two points is shown.(a) Determine the electric current in this part of the circuit and show its direction o
Iowa State - PHYSICS - 112
HOMEWORK for JUNE 30, 2005 For the following circuits, draw the circuit and fill out the V M ?Z T table (including the battery or batteries). Also mark a point between each pair of circuit elements (resistors or batteries) and determine the electric poten
Iowa State - PHYSICS - 112
HOMEWORK for JUNE 30, 2005 For the following circuits, draw the circuit and fill out the V M ?Z T table (including the battery or batteries). Also mark a point between each pair of circuit elements (resistors or batteries) and determine the electric poten
Iowa State - PHYSICS - 112
HOMEWORK for TUESDAY, JULY 5, 2005Determine the currents in the following circuits, and construct the V M ?Z T table for each circuit. Check that the powers are correct. Also, determine the electric potentials at the points marked.
Iowa State - PHYSICS - 112
Determine the currents in the following circuits, and construct the V M ?Z T table for each circuit. Check that the powers are correct. Also, determine the electric potentials at the points marked.V 6H 12 H 4HM 2A 1A 3A?Z 12 V 12 V 12 VT 24 W 12 W 36
Iowa State - PHYSICS - 112
HOMEWORK for THURSDAY JULY 7, 2005 1. Determine the magnitude and direction of the magnetic force on the following charges in a magnetic field of 0.20 T directed east: (a) A charge ; oe 4.0 .C moving north at 35 m/s.(b) An electron moving vertically upwa
Iowa State - PHYSICS - 112
HOMEWORK for TUESDAY, JULY 12, 2005For each of the following situations two circuit loops are shown in a uniform t external magnetic field F . Let the one on the left have a clockwise current and the one on the right have a counterclockwise current. Dete
Iowa State - PHYSICS - 112
HOMEWORK for TUESDAY, JULY 12, 2005For each of the following situations two circuit loops are shown in a uniform t external magnetic field F ext . Let the one on the left have a clockwise current and the one on the right have a counterclockwise current.
Iowa State - PHYSICS - 112
Homework for Thursday, July 14, 2005 (Bastille Day) Name _ Section _For each of the following situations a circuit loop is shown in a uniform t external magnetic field F . Determine in each case the direction (clockwise or counterclockwise) of the induce
Iowa State - PHYSICS - 112
C 1. t F ext BThe magnitude F of the magnetic field is increasing.Flux: increasing due to increasing F . t F loop must be down ( OE ) to counteract upward increasing flux; current is then clockwise.C 2. t OE F ext BThe magnitude F of the magnetic fiel
Iowa State - PHYSICS - 112
HOMEWORK FOR TUESDAY, JULY 19, 2005 In this problem we will consider the path of light rays from air into glass and vice versa. The glass has a flat, horizontal surface, and the air is above it. We want to determine the angles for the reflected and refrac
Iowa State - PHYSICS - 112
HOMEWORK SOLUTIONS FOR JULY 21 1. An object is placed 10 cm from the vertex of a concave mirror of radius of curvature 12 cm. Find the image distance and the magnification, and characterize the image in the usual way. Check your results by ray tracing usi
Iowa State - PHYSICS - 112
HOMEWORK ASSIGNMENT FOR JULY 26, 2005Consider the interference between two slits separated by a distance . on which light of wavelength - shines, producing a pattern of dark and bright fringes on a screen a distance H away from the slits. First draw a sk
Iowa State - PHYSICS - 112
Consider the interference between two slits separated by a distance . on which light of wavelength - shines, producing a pattern of dark and bright fringes on a screen a distance H away from the slits. First draw a sketch of this physical situation, showi
Iowa State - PHYSICS - 112
HOMEWORK FOR THURSDAY, JULY 28, 20051. A diffraction grating has lines spaced 2.00 .m apart. Let's consider white visible light (wavelengths ranging from 0.400 .m for violet light to 0.700 .m for red light) shining on it. (a) Determine all the angles for
Iowa State - PHYSICS - 112
SOLUTIONS 1. A diffraction grating has lines spaced 2.00 .m apart. Let's consider white visible light (wavelengths ranging from 0.400 .m for violet light to 0.700 .m for red light) shining on it. (a) Determine all the angles for which interference maxima
Iowa State - PHYSICS - 112
HOMEWORK FOR TUESDAY, AUGUST 2, 20051. Consider the atom denoted by 183 Au 79 The common name of this element is _. It has _ electrons, _ protons, _ neutrons, and _ quarks. This atom is radioactive and decays by alpha decay with a half-life of 49 seconds
Iowa State - PHYSICS - 112
1. Consider the atom denoted by 183 Au 79 The common name of this element is: gold It has 79 electrons, 79 protons, and 183 79 oe 104 neutrons. This atom is radioactive and decays by alpha decay with a half-life of 49 seconds. Determine the fraction of it
Iowa State - PHYSICS - 112
REFRACTION WORKSHEET &quot;Triangle&quot; Diagram: On other pages in this set you will find a large triangle that represents a triangular prism. We want to follow the path of a light ray striking one of the surfaces as it passes through the prism and exits one of t
Iowa State - PHYSICS - 112
PHYSICS 112 - REVIEW FOR EXAM 1ELECTRIC CHARGES Electric charges are positive, negative, or zero; they are measured in coulombs (symbol: C). Electric charges are quantized: every object in the universe has a electric charge ; oe , 8/, where 8 oe 0, 1, 2,
Iowa State - PHYSICS - 112
PHYSICS 112 - REVIEW FOR EXAM 2CURRENT M rate at which electic charge is flowing in a wire M oe ?UX RESISTANCE V and POTENTIAL DIFFERENCE ?Z related by Ohm's law: ?Z oe MV . The power dissipated in a resistor has magnitude T oe M ?Z oe M 2 V oe ?Z 2 V .
Iowa State - PHYSICS - 112
PHYSICS 112 - REVIEW FOR EXAM 3t MAGNETIC FLUX: The magnetic flux through a plane circuit is F oe FE cos ), where ) is the angle between F 2 and the normal ( perpendicular) to the plane of the circuit. Units: T-m . MAGNETIC INDUCTION The current induced
Iowa State - PHYSICS - 112
PHYSICS 112 - SPRING 2003 - EXAM 1 - February 12, 2003 Name: _ Recitation Section Number: _ SHOW YOUR WORK! Although some of these problems are multiple-choice, full credit will be given only if you explain how you arrived at your answer. Either show your